tarnfeld
tarnfeld

Reputation: 26566

Simple Properties in Objective-C Classes

I've bene working with Objective-C for a while now, and so far I have never really needed to craft my own classes, properly.

I am a bit confused with the two arguments you can give the @property(a, b) declaration in a header file. When creating outlets to Interface Builder I usually do @property(nonatomic, retain) but I have no idea what this means.

I'm writing a simple class which has a set of properties which will be set from the outside, like [instance setName:@"Bla Bla Bla"]; or I guess like instance.name = @"Bla@" but I would rather the first option.

How would I declare this kind of property on a class?

Thanks in advanced! Sorry for the n00bish question :-)

Upvotes: 2

Views: 254

Answers (1)

Julien
Julien

Reputation: 3477

The @property parameter gives you a hint on the property behavior:

nonatomic tells you that setting/getting the property value is not atomic (wrt to multiple thread access)

retain tells you the object will be retained by the property (i.e. The receiver will take ownership of the object). The othe options are "copy" (the object is copied using -copy. This is generally the good choice for value objects like NSStrings) and "assign" (the object is just assigned to the property without retaining it. This is generally the good choice for delegates or datasources). These 3 options are only useful for ObjC objects, not simple C type properties.

See http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html for more info.

For your case, you'll likely use:

@property(copy) NSString* name;

Or:

@property(nonatomic, copy) NSString* name;

If you don't need the property setter/getter to be atomic.

Upvotes: 1

Related Questions