开发者

Retain and Assign in Objective C

I want to know the difference between the r开发者_开发知识库etain and assign in Objective C


When working with Objective-C objects,

assign creates a reference from one object to another without increasing the source's retain count.

retain creates a reference from one object to another and increases the retain count of the source object.

aColor is the source object. Say it has a retain count of 400 coming into the method.

-(void) changeColor:(UIColor *)aColor
{
   UIColor *alpha = aColor; // aColor retain count = 400 still

   UIColor *beta = [aColor retain]; // aColor retain count now 401
}

alpha and beta are both references to the object aColor. The simple assignment of alpha does not affect the source object in any way. alpha is just another pointer to aColor.

beta is still just another pointer to aColor, but the -retain has the additional effect of increasing its retain count by 1.

When you declare a property to use retain,

@property (retain) UIColor *color;

the compiler will generate a set accessor that assigns the argument value to the ivar as well as retains the source argument. Essentially,

-(void)setColor:(UIColor *)aColor
 {
   ...
   color = [aColor retain];
 }

When you declare a property to use assign,

@property (assign) UIColor *color;

you get the ivar assignment without any change in the source argument.

-(void)setColor:(UIColor *)aColor
 {
   ...
   color = aColor;
 }


this is what happens in the setter provided automatically when a property is "retain"

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

this is instead what happens when you have "assign"

- (void)setValue: (id)newValue
{
    if (value != newValue)
    {
        value = newValue;
    }
}


Retain tells the compiler to send a retain message to any object we assign to the property. This keeps the instance variable alive (and not releasing it) when using it.

Assign is intended for use with low level C datatypes or with garbage collection. GC is not under any feature for the iOS either.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜