How is retain setter implemented with @synthesize?

前端 未结 6 979
逝去的感伤
逝去的感伤 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:31

    A synthesized retained setter looks like :

    - (void)setValue: (id)newValue
    {
        if (value != newValue)
        {
            [value release];
            value = newValue;
            [value retain];
        }
    }
    

    In your case, you have two valid methods :

    1) Create a temp var, alloc/init (= retained), set to property, release.

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

    2) No temp var, set directly to ivar.

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

    UPDATE: If you use method 2), you have to explicitly handle the rest of memory management (not only retaining), by releasing any previous value it might have before if needed. If done only once in init (for instance), you can just put a [overlay release]; in dealloc.

提交回复
热议问题