Home » Ios » Objective C – Assign, Copy, Retain

Objective C – Assign, Copy, Retain

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m new to Objective C. I have basic knowledge in C, including the concept of pointers. I have two basic questions:

  1. Can someone explain the difference between assign,copy, and retain with some analogy?
  2. How do you handle a function which returns pointer variable, and how do you perform messaging through a return pointer?
Answers:

Updated Answer for Changed Documentation

The information is now spread across several guides in the documentation. Here’s a list of required reading:

The answer to this question now depends entirely on whether you’re using an ARC-managed application (the modern default for new projects) or forcing manual memory management.

Assign vs. Weak – Use assign to set a property’s pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you’ll want to use weak so you’re not trying to access a deallocated object (illegal access of a memory address – “EXC_BAD_ACCESS“) if you don’t perform proper cleanup.

Retain vs. Copy – Declared properties use retain by default (so you can simply omit it altogether) and will manage the object’s reference count automatically whether another object is assigned to the property or it’s set to nil; Use copy to automatically send the newly-assigned object a -copy message (which will create a copy of the passed object and assign that copy to the property instead – useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).

Questions:
Answers:

The Memory Management Programming Guide from the iOS Reference Library has basics of assign, copy, and retain with analogies and examples.

copy
Makes a copy of an object, and returns it with retain count of 1.
If you copy an object, you own the copy. This applies to any method that contains the word copy where “copy” refers to the object being returned.

retain Increases the retain count of an object by 1. Takes ownership of
an object.

release Decreases the retain count of an object by 1. Relinquishes
ownership of an object.

Questions:
Answers:

Copy vs Assign vs Retain

Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.

A hidden feature

NSString * string ;

When You call this expression

string = @"Your name";

a method will automatically called

- (void)setString:(NSString*)newString
{
        
}
  • Assign

In your setter method for the property, there is a simple assignment
of your instance variable to the new value,

- (void)setString:(NSString*)newString
{
        
   string = newString;
}

This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.

  • Retain

this retains the new value in your setter method. For example: This
is safer, since you explicitly state that you want to maintain a
reference of the object, and you must release it before it will be
deallocated.

- (void)setString:(NSString*)newString
{
         
       [newString retain];
         
       [string release];
           
       string = newString;
        
}
  • Copy

this makes a copy of the string in your setter method: This is often
used with strings, since making a copy of the original object ensures
that it is not changed whilst you are using it.

    - (void)setString:(NSString*)newString
     {
           
             if(string!=newString){
             
                            [string release];
             
                            string = [newString copy];
           
       }
    
     }

Questions:
Answers:

· Assign is for primitive values like BOOL, NSInteger or double. For objects use retain or copy, depending on if you want to keep a reference to the original object or make a copy of it.
· assign: In your setter method for the property, there is a simple assignment of your instance variable to the new value, eg:

-(void)setString:(NSString*)newString{
     
        string = newString;

    }

This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.
· retain: this retains the new value in your setter method. For example:
This is safer, since you explicitly state that you want to maintain a reference of the object, and you must release it before it will be deallocated.

- (void)setString:(NSString*)newString{
     
        [newString retain];
     
          [string release];
       
 string = newString;
    
}

· copy: this makes a copy of the string in your setter method:
This is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.

- (void)setString:(NSString*)newString{
       
         if(string!=newString){
         
                        [string release];
         
                        string = [newString copy];
       
         }

    }

Questions:
Answers:
  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”
Questions:
Answers:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"First",@"Second", nil];
NSMutableArray *copiedArray = [array mutableCopy];
NSMutableArray *retainedArray = [array retain];

[retainedArray addObject:@"Retained Third"];
[copiedArray addObject:@"Copied Third"];

NSLog(@"array = %@",array);
NSLog(@"Retained Array = %@",retainedArray);
NSLog(@"Copied Array = %@",copiedArray);

array = (
    First,
    Second,
    "Retained Third"
)
Retained Array = (
    First,
    Second,
    "Retained Third"
)
Copied Array = (
    First,
    Second,
    "Copied Third"
)

Questions:
Answers:

retain vs. copy vs. assign

assign” is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that “assign” should be used for non-pointer attributes.

retain” is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.

copy” is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don’t want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.