Automatic iVars with @synthesize

后端 未结 3 1770
再見小時候
再見小時候 2021-01-01 01:48

I understand that starting with iOS 4, there is now the ability to not declare iVars at all, and allow the compiler to automatically create them for you when you synthesize

相关标签:
3条回答
  • 2021-01-01 01:58

    You can directly access instance variables using -> symbol instead of dot . (which will invoke ivar's corresponding accessor method):

    .h

    @interface myClass {
    }
    @property(nonatomic, retain) NSIndexPath *indexPath
    
    @end
    

    .m

    @implementation myClass
    
    - (void)dealloc {
        [self->indexPath release];
        self->indexPath = nil; // optional, if you need it
    
        [super dealloc];
    }
    @end
    

    Thus you will directly access iVar and not it's corresponding accessor method, obtaining additional benefit - performance.

    0 讨论(0)
  • 2021-01-01 02:13

    I've went through many different ways of dealing with this. My current method is to use the property access in dealloc. The reasons not to are too contrived (in my mind) to not do it, except in cases where I know the property has odd behavior.

    @interface Class
    @property (nonatomic, retain) id prop;
    @end
    
    @implementation Class
    @synthesize prop;
    
    - (void)dealloc;
    {
        self.prop = nil;
        //[prop release], prop=nil; works as well, even without doing an explicit iVar
        [super dealloc];
    }
    @end
    
    0 讨论(0)
  • 2021-01-01 02:15

    In constrast, I do the following:

    @interface SomeViewController : UIViewController
    
    @property (nonatomic, copy) NSString *someString;
    
    @end
    

    and then

    @implementation SomeViewController
    
    @synthesize someString;
    
    - (void)dealloc
    {
        [someString release], someString = nil;
        self.someString = nil; // Needed?
    
        [super dealloc];
    }
    
    @end
    

    Note: At some point Apple will enable synthesize-by-default which will no longer require the @synthesize directive.

    0 讨论(0)
提交回复
热议问题