If I 开发者_StackOverflow中文版have a Class (MyClass) with an attribute myAttribute, I can't use it in a subclass (MySubclass) without calling self.myAttribute. I have not problem with this sort of code when running the app with the simulator. You might be wondering: "why does she do this?". It's quite easy to add "self" everywhere. The problem is that in MySubclass I'm overriding some accessor methods of MyClass. Here's an example:
- (NSDateFormatter *)dateFormatter
{
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
// Do other stuff with the dateFormatter
}
return dateFormatter;
}
I can't call self.dateFormatter inside of the getter because it would create an endless loop. I can refactor my classes to deal with that problem but it might be a good and simple solution to deal with that kind of problem.
Thanks!
You have to remember that self.property is the very same as [self propertyGetter].
Property name and instance variable shall not share the same name to avoid any confusion.
Best way is to always preprend a common prefix to ivars.
@interface MyClass {
// You don't have to declare iVar. Feel free to remove line.
NSDateFormatter * iVarDateFormatter;
}
@property (retain) NSDateFormatter * dateFormatter;
@end
And at implementation
@implementation MyClass
@synthetize dateFormatter= iVarDateFormatter;
...
@end
So you can write:
- (NSDateFormatter *) dateFormatter
{
if ( nil == iVarDateFormatter )
{
iVarDateFormatter = [[NSDateFormatter alloc] init];
// Do other stuff with the dateFormatter
}
return iVarDateFormatter;
}
Even better for singleton objects as this one, use GCD dispatch_once!
- (NSDateFormatter *) dateFormatter
{
static dispatch_once_t pred;
dispatch_once(& pred, ^{
iVarDateFormatter = [[NSDateFormatter alloc] init];
// Do other stuff with the dateFormatter
});
return iVarDateFormatter;
}
精彩评论