Extending properties generated by @synthesize in Objective-C

Suppose I have @property declared as follows:

@property (readwrite,retain) NSObject *someObject; 

And I synthesize it like this:

 @synthesize someObject = _someObject; 

This creates getters / seters for me. In addition, according to the documents, the installer will have a built-in thread safety code.

Now suppose I want to add code to the setSomeObject: method. Is there any way to extend existing from @synthesize? I want to be able to reuse the thread security code that it auto-generates.

+1
source share
2 answers

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 this method.

However, as you said, this code cannot be thread safe.

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

+1
source

You can define the synthesized property "private" (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 the 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; } 

Now you can access the someObject "property, as usual, for example. object.someObject . You also get the advantage of automatically generated retain / release / copy , compatibility with ARC and almost no loss of thread safety.

+3
source

Source: https://habr.com/ru/post/1335801/


All Articles