Is it safe to say that if a class member does not need getter or setter functions then there's no point in making them properties and synthesizing them?
+2
A:
Well, yes, but often properties can be helpful in the implementation itself even if the properties won't be set outside of the implementation.
For example, suppose you had
@interface SomeObject : NSObject {
NSThing *thing;
}
@end
@implementation SomeObject
- (id)init {
if((self = [super init]))
thing = [[NSThing someThing] retain];
return self;
}
- (void)someMethod {
if(thing)
[thing release];
thing = [[NSThing someOtherThing] retain];
}
// etc etc
@end
Why would you want to bother having to check if thing
had been allocated, release thing
, set it to something else, and then retain
it again, when you could simply do:
- (id)init {
if((self = [super init]))
[self setThing:[NSThing someThing]];
return self;
}
- (void)someMethod {
[self setThing:[NSThing someOtherThing]];
}
If you don't want to make these properties accessible outside of your class, you can use a category
@interface SomeObject ()
@property (retain) NSThing *thing;
@end
in your .m file.
anshuchimala
2010-08-14 02:01:08
That's actually called a class extension. A category *should* have both a separate interface and a separate implementation (although the compiler does currently let you get away without a separate implementation), but a class extension is simply a continuation of the class's main interface, so the methods it declares must be implemented in the class's main implementation, the same as any methods declared in the class's actual main interface.
Peter Hosey
2010-08-14 05:46:51
Also, you should generally not use accessors in your `init` methods and `dealloc` method. If you define a custom accessor, or a subclass overrides your accessor, the accessor may be unsafe to use on a half-inited/half-deallocated object. You should use accessors everywhere else in the class, but should avoid them in `init` methods and `dealloc`.
Peter Hosey
2010-08-14 05:48:33