views:

190

answers:

1

Hello! I have an Objective-C NSMutableDictionary declared inside a class's @interface section, with getter/setter methods, like so:

@interface myClass : NSObject
{
     NSMutableDictionary *dict;
}
- (void) setDict: (NSMutableDictionary *) newDict;
- (NSMutableDictionary *) dict;

Inside some of my @implementation methods I want to modify dict. I'd like to stick to standard Obj-C idiom and modify it "properly". Is it OK to modify it like this, using the getter but not the setter:

[[self dict] removeObjectForKey:@"myKey"];

...or is there a better way to do this?

+3  A: 

That'll work, but why not do:

[dict removeObjectForKey:@"myKey"];

Inside a class's implementation, you have direct access to the instance variables, and using them directly is idiomatic Objective-C.

mipadi
I was under the impression that you should always access variables via their Getter methods, rather than directly. However I'm very new to the language, so I very well may be wrong about this.
Dave Gallagher
It's not (usually) necessary to use the accessor method within the class's own implementation; of course, outside classes should use the accessor methods.
mipadi
Ah, excellent! Thanks!That begs the question though, when is it necessary to use the accessor method inside the class's own implementation? Would it be when you've, say, created your own custom accessors which do something funky, like increment a counter whenever a variable is read?
Dave Gallagher
lots of times devs use the property setters from inside as an easy way to cheat reference counting
slf
This particular usage has nothing to do with "cheating reference counting", since it doesn't affect the retain count of the variable. Using a setter isn't cheating — in many cases, it's the new, smart way to do things.
Quinn Taylor