What is the best approach in terms of:
- security and control of leaks?
- performance?
- visibility outer the class?
First: keeping control of each variable
if (objectProperty_ != anObject) {
[objec开发者_StackOverflow中文版tProperty_ release];
objectProperty_ = [anObject retain];
}
Second: declaring properties and using the accessors and letting the system do the work
@property (nonatomic, readwrite, retain) NSObject *objectProperty;
...
@synthesize objectProperty = objectProperty_;
...
self.objectProperty = anObject;
Thank you.
Use properties wherever possible.
- They save you having to write lots of boilerplate accessor methods. In the days before properties, probably every Cocoa programmer had a pair of macros that they used to define accessors.
@property
automatically documents the semantics of the accessor. For instance in your example, I can see from the interface that objectProperty retains its value, rather than assigns it or copies it.
Point 2 even holds when you declare properties but define your own accessors.
The approach that is most likely to preserve your sanity is to use Apple-written accessors when you can, and write your own when you must.
The accessor method call does add a slight amount of time; I timed this on my iPad, and I think it was about 10^-7 seconds. This should be true regardless of whether you write the method yourself or use Apple's. In all but the most extreme situations, that is unlikely to matter.
Less code means less bugs, so just use property to get-set if you have to declare read-write property for public access.
精彩评论