I’m declaring an NSString property in a class and objective-c is complaining that:
NSString no ‘assign’, ‘retain’, or ‘copy’ attribute is specified
It then casually lets me know that “assign is used instead”.
Can someone explain to me the difference between assign, retain and copy in terms of normal C memory management functions?
I think it is drawing your attention to the fact that a
assignis being used, as opposed toretainorcopy. Since anNSStringis an object, in a reference-counted environment (ie without Garbage Collection) this can be potentially “dangerous” (unless it is intentional by design).However, the difference between
assign,retainandcopyare as follows:assign: In your setter method for the property, there is a simple assignment of your instance variable to the new value, eg:
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.
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.