Sam Lee
Sam Lee

Reputation: 7199

Extending properties generated using @synthesize in Objective-C

Suppose I have an @property declared like this:

@property (readwrite,retain) NSObject *someObject;

And I synthesize it like this:

@synthesize someObject = _someObject;

This generates getters/setters for me. Also, according to the docs, the setter will have built in thread safety code.

Now, suppose I want to add some code to the setSomeObject: method. Is there any way that I can extend the existing on from @synthesize? I want to be able to reuse the the thread safety code that it autogenerates.

Upvotes: 1

Views: 1027

Answers (2)

user1071136
user1071136

Reputation: 15725

You can define a synthesized "private" property, (put this in your .m file)

@interface ClassName ()

// Declared properties in order to use compiler-generated getters and setters
@property (nonatomic, strong <or whatever>) NSObject *privateSomeObject;

@end

and then manually define a getter and setter in the "public" part of ClassName (.h and @implementation part) like this,

- (void) setSomeObject:(NSObject *)someObject {
  self.privateSomeObject = someObject;
  // ... Additional custom code ...
}

- (NSArray *) someObject {
  return self.privateSomeObject;
}

You can now access the someObject "property" as usual, e.g. object.someObject. You also get the advantage of automatically generated retain/release/copy, compatibility with ARC and almost lose no thread-safety.

Upvotes: 3

Can Berk G&#252;der
Can Berk G&#252;der

Reputation: 113300

What @synthesize does is equivalent to:

-(void)setSomeObject:(NSObject *)anObject {
    [anObject retain];
    [someObject release];
    someObject = anObject;
}

or

-(void)setSomeObject:(NSObject *)anObject {
    if(someObject != anObject) {
        [someObject release];
        someObject = [anObject retain];
    }
}

so you can use this code and extend the method.

However, as you said, this code might not be thread-safe.

For thread safety, you might want to take a look at NSLock or @synchronized (thanks to unwesen for pointing this out).

Upvotes: 1

Related Questions