memory-management-program

  • Summery: 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 simpe assignment of your instance variable to the new value.

    1
    2
    3
    -(void)setString: (NSString *)newString{     
    string = newString;
    }
  • .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 object, and you must release it before it will be deallocated.

    1
    2
    3
    4
    5
    (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.

    1
    2
    3
    4
    5
    6
    (void)setString:(NSString *)newString{  
    if(string != newString) {
    [string release];
    string = [newString copy];
    }
    }
  • .weak: use weak references to avoid retain cycles
    An illustration of cyclical references

Reference: