3

I have to write the methods as C Function so as to access the object every time, I want to declare that object inside the function and allocate it. How can I maintain a common object in all C Functions. Is it Possible?

void method1
{
    NSMutableArray *sample = [[NSMutableArray alloc]init];
}

void method2
{
    NSMutableArray *sample = [[NSMutableArray alloc]init];
}
2
  • 3
    make it a global variable? or a class variable? Commented Aug 22, 2012 at 12:03
  • @FaddishWorm make it Global variable Commented Aug 22, 2012 at 12:06

4 Answers 4

2

I believe this should work (although this is definitely not thread-safe):

NSMutableArray *sample = nil;

void method1 {
    if (sample == nil) {
        setupSample();
    }
    // ...
}

void method2 {
    if (sample == nil) {
        setupSample();
    }
    // ...
}

void setupSample {
    sample = [[NSMutableArray alloc] init];
    // Any other setup here
}
Sign up to request clarification or add additional context in comments.

Comments

1
 static NSMutableArray *sampleArray=nil;
 @implementation class
 void method1(void){
    if (sampleArray ==  nil){
       sampleArray = [[NSMutableArray alloc]init];
     }
  }                     
  void method2(void){
    if (sampleArray ==  nil){
       sampleArray = [[NSMutableArray alloc]init];
     }
}

kindly use this

Comments

1

You may want to use class methods to access a shared object.

something like...

void method {
NSMutableArray *mySharedObj = [SampleRelatedContextClass sample];
}

This just looks better.

Comments

0

Create static file-scoped variable.

static NSMutableArray *sample=nil;

@implementation class

void method1(){ //you can write c functions outside  @implementation also
if (sample==nil) {
        sample = [[NSMutableArray alloc]init];
    }   

}

void method2(){
if (sample==nil) {
    sample = [[NSMutableArray alloc]init];
}
}
@end   

NOTE: You can not use objective-c instance variable in c functions

1 Comment

Technically, that's not a global variable, it's a static file-scoped variable. It just means it cannot be extern'd into other source files, basically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.