How can I access an instance variable in a class method in Objective-C?

I am developing an application in which I implement the method.h class. How can I access an instance variable in a class method?

Here is my instance method and an object of class "SomeClass" is created:

-(void)viewDidLoad
{
   SomeClass *obj=[SomeClass alloc] init];
}

Here is the class method and in this method I am trying to access the instance variable 'obj', so I got an error saying "instance variable" obj "accessing the class method".

+(void)classMethodImplement
{

}
+5
source share
3 answers

You cannot access instance variables from class methods. Since instance variables are bound to specific instances of the class, access to them from the class method does not make sense, therefore, the language does not allow it.

+15

. .

1:

, , :

static id static_iVar = nil;
- (void)viewDidLoad {
    // blah, blah, blah
    static_iVar = _iVar;
}

2:

self , iVars :

static id static_self = nil;
- (void)viewDidLoad {
    // blah, blah, blah
    static_self = self;
}

, , . , , , .

-, :

+(void)classMethodImplement
{
    // Use it here...
}
+9

Rewrite the class method so that its caller provides the required object.

+(void)classMethodImplement:(SomeClass *)obj
{
}
+4
source

All Articles