How is retain setter implemented with @synthesize?

前端 未结 6 974
逝去的感伤
逝去的感伤 2020-12-10 19:01

I have the following in the header:

@property (nonatomic, retain) UIView *overlay;

And in the implementation:

@synthesize o         


        
6条回答
  •  温柔的废话
    2020-12-10 19:49

    As your property is defined with (retain) any instance you set using the synthesized setter (via the self.overlay syntax) will automatically be sent a retain message:

    // You're alloc'ing and init'ing an object instance, which returns an 
    // instance with a retainCount of 1.
    UIView *tempOverlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];
    
    // The overlay property is defined with (retain), so when you assign the new 
    // instance to this property, it'll automatically invoke the synthesized setter, 
    // which will send it a retain message. Your instance now has a retain count of 2.
    self.overlay = tempOverlay;
    
    // Send a release message, dropping the retain count to 1.
    [tempOverlay release];
    

    If you were to do:

    self.overlay = [[UIView alloc] initWithFrame:CGRectMake(160.0f, 70.0f, 150.0f, 310.0f)];
    

    Your overlay would have a retain count of two, which will likely lead to a leak at some point in your application.

提交回复
热议问题