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.
@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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With