DIFFERENCE- COPY VS ASSIGN VS RETAIN

Tarun Kumar

Total Post:107

Points:535
Posted by  Tarun Kumar
 963  View(s)
Ratings:
Rate this:
  1. Tarun Kumar

    Post:107

    Points:535
    Difference- 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. 

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

    (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];

    }

    }

      Modified On Oct-06-2015 12:18:45 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!