Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property from a class method?

In order to make my code testable, I have created a lazy initializer; this way in my unit test, I can mock any object I want before the getter gets called.

When it comes to class methods, though, my class method doesn't have access to the properties I have defined.

  1. Is there any way to make the properties accessible by my class method?
  2. If not, is there any way to create static variables that are also accessible outside of this class, i.e., accessible by my unit test class?

@implementation
@synthesize webService;

+ (void)doSomething
{
   self.webService.url = @"some url";
   [self.webService start];
   // do other things
}

- (WebService*)webService
{
   if (!webService)
   {
      webService = [[WebService alloc] init];
   }
   return webService;
}

@end
like image 379
aryaxt Avatar asked Dec 21 '22 15:12

aryaxt


1 Answers

By definition a class method cannot have state so that means that it can't access variables that are supposed to be a part of an "instance." In an instance method (one that starts with a "-"), the self pointer refers to the instance the method is being called on, however, in a class method (one that starts with a "+") "self" refers to the class itself, not a specific instance. This means there is no way to access properties directly.

However, one way to do this would be to create a static instance of your class within the implementation file:

static WebService* webService;

then you would use something like a "sharedInstance" method to get access to it so you can make sure to allocate the variable:

+(WebService*)sharedInstance
{
    if( nil == webService )
    {
        webService = [[WebService alloc] init];
    }
    return webService;
}

Another option is to define static variables in your implementation file, and then create class methods to set and get them from other files / classes.

like image 145
drewag Avatar answered Dec 28 '22 05:12

drewag