aryaxt aryaxt - 11 days ago 7
Objective-C Question

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

Answer

Looks like you need a singleton.

<...>

Upd: If this way isn't acceptable, here are direct answers to your questions:

Is there any way to make the properties accessible by my class method?

No. You have to create an instance in some way.

If not is there any way to create statis variables that are also accessible outside of this class? (Accessible by my unit test class

Yes. You can create static or global variables that will keep instances. They will be accesible from outside your class. Static variable is accesible within the source file where it is defined; and global variable is accessible from everywhere. If you wand to deal with global variable, you define it in your *.m file

MyClass *my_inst;

and you make declaration in *.h file:

external MyClass *my_inst;