Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C 101 (retain vs assign) NSString

A 101 question

Let's say i'm making database of cars and each car object is defined as:

#import <UIKit/UIKit.h>

@interface Car:NSObject{
    NSString *name;
}

@property(nonatomic, retain) NSString *name;

Why is it @property(nonatomic, retain) NSString *name; and not @property(nonatomic, assign) NSString *name;?

I understand that assign will not increment the reference counter as retain will do. But why use retain, since name is a member of the todo object the scope of it is to itself.

No other external function will modify it either.

like image 736
qstar Avatar asked Sep 04 '09 16:09

qstar


3 Answers

There's no such thing as the "scope of an object" in Objective-C. Scope rules have nothing to do with an object's lifetime — the retain count is everything.

You usually need to claim ownership of your instance variables. See the Objective-C memory management rules. With a retain property, your property setter claims ownership of the new value and relinquishes ownership of the old one. With an assign property, the surrounding code has to do this, which is just as mess in terms of responsibilities and separation of concerns. The reason you would use an assign property is in a case where you can't retain the value (such as non-object types like BOOL or NSRect) or when retaining it would cause unwanted side effects.

Incidentally, in the case of an NSString, the correct kind of property is usually copy. That way it can't change out from under you if somebody passes in an NSMutableString (which is valid — it is a kind of NSString).

like image 128
Chuck Avatar answered Nov 16 '22 14:11

Chuck


and don't forget to access it via

self.name = something;

because

name = something;

will not care about the generated setter/getter methods but instead assign the value directly.

like image 19
Axel Avatar answered Nov 16 '22 13:11

Axel


Without retain there is no guarantee the NSString* you are setting name with will live any longer than the assignment statement itself. By using the retain property for the synthesized setter you're allowing it to tell the memory management system that there is at least one more object interested in keeping the NSString* around.

like image 12
fbrereto Avatar answered Nov 16 '22 14:11

fbrereto