Alex Rivera | Logout

Objective-C 101 (retain vs assign) NSString

Asked 2009-09-04T16:40:18.383
54

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.

Edit
Report

3 Answers

19

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.

answered 2011-01-11T16:23:46.510
3

Google's Objective-C Style Guide covers this pretty well:

Setters taking an NSString, should always copy the string it accepts. Never just retain the string. This avoids the caller changing it under you without your knowledge. Don't assume that because you're accepting an NSString that it's not actually an NSMutableString.

answered 2012-03-12T17:18:46.253
2

Would it be unfortunate if your class got this string object and it then disappeared out from under it? You know, like the second time your class mentions that object, it's been dealloc'ed by another object?

That's why you want to use the retain setter semantics.

answered 2011-01-11T16:13:30.543

Your Answer