简体   繁体   中英

Retain and Assign in Objective C

我想知道Objective C中retain和assign之间的区别

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM