Objective C 2.0 properties and storage keywords

11.12.2009 21:11 in ObjC

@interface Foo : NSObject
{
  NSString *_foo;
}
@property NSString *foo;
@end

@implementation Foo : NSObject
@dynamic foo;
- (void) setFoo:(NSString*)value
{
  [_foo release];
  _foo = value;
  [_foo retain];
  [self doSomethingFancyWithNewFoo];
}
- (NSString*) foo
{
       return _foo;
}
@end

This code is quite cool. However, a problem arises. Here we go.

warning: 'assign' attribute (default) not appropriate for non-gc object property 'foo'
warning: no 'assign', 'retain', or 'copy' attribute is specified - 'assign' is assumed

OK. We have 3 options:

  • @property (assign) NSString *foo
  • @property (retain) NSString *foo
  • @property (copy) NSString *foo

I assume you know what those values would mean in @synthesize. But do they have any meaning with @dynamic properties?

Answer is: no. They have no meaning at all. I changed NSString to my own class doing a lot of NSLogging and usage of assign/retain/copy is completely meaningless.

I suppose the same goes for (non)atomic keywords. So why do we have to write down those keywords anyway? I have no idea. Should it be a hint for class' user? But dynamic property doesn't need to store its data in variable. I'm aware that class' clients know nothing about implementation (is is synthesized or dynamic). But I think that there should be dynamic storage keyword. So that we could write:

@property (dynamic[, readwrite]) NSString *foo;

If you are Obj-C expert and know better explanation, let me know. :)