开发者

App doesn't run on the device - I can't call an attribute's class from its subclass without using self.attribute

开发者 https://www.devze.com 2023-04-03 16:53 出处:网络
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 c

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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号