1

test.h

NSString *name;
@property(nonatomic,retain) NSString *name;

test.m

@synthesize name;

here why did we use nonatomic , retain in the property and in .m file why we are using @synthesize ?

please answer ,

Rais Alam
  • 6,742
  • 11
  • 50
  • 84
jaleel
  • 1,153
  • 8
  • 22
  • 44

2 Answers2

2

Apple Documentation

nonatomic is described in detail here.

retain means that the property is retained when the value is set to anything other than nil. There are other options such as copy and assign. Normally object types that can be copied should use copy, like NSString. assign simply sets the pointer value.

@synthesize stubs out the getter and setter methods for the property and is required in order for the nonatomic and retain to work.

Also, make sure that if you use retain or copy, that you also release the object in the dealloc method.

- (void)dealloc {
    [name release];
    [super dealloc];
}
Community
  • 1
  • 1
tidwall
  • 6,587
  • 33
  • 44
  • `nonatomic` doesn't have much to do with thread safety. It just means that you'll always get a viable value in a threaded environment. Whether it is right or not is not guaranteed (i.e. atomicity is not a transaction system). – bbum Nov 03 '10 at 06:23
  • Good post, but why would you want to `copy` objects when you don't really have to ? Especially if you're using immutable objects (like NSString) copying is only a waste of memory. I very rarely found the need for `copy` so far. – DarkDust Nov 03 '10 at 06:26
  • @DarkDust: Every NSMutableString is a valid NSString. You don't want to accidentally store one of those and have it change under you. Most objects that implement copy at least *could* be mutable. Therefore, it's a good idea to declare all properties that way. Also, as an optimization, NSString (the immutable version) merely retains when you tell it to copy. – Chuck Nov 03 '10 at 06:33
  • @bbum: Thanks for the clarification. I always assumed that pointer value returned by the getter would be thread-safe when atomic+synthesize was used. – tidwall Nov 03 '10 at 06:47
  • 2
    It is safe in that you'll get back something valid. Consider; you have `firstName`, `lastName` and `fullName` (which combines the two) properties. No amount of `@property` atomicity will protect against setting first name, then last name, while 2nd thread calls for full name in the middle of that.... – bbum Nov 03 '10 at 07:02
1

The nonatomic means that setting the property is not thread-safe, retain means new value is retained (and the old value released), and the @synthesize actually creates the methods that are necessary for the property. In this case, it evaluates to something like this:

- (NSString *)name {
    // Method "name", returning content of variable "name".
    return name;
}

- (void)setName:(NSString *)newName {
    [newName retain];
    [name release];
    name = newName;
    // Also some magic for KVO is added here.
}
DarkDust
  • 85,893
  • 19
  • 180
  • 214