A complete raw list of KVC accessor selector formats
Implementing and using (i.e., calling) these accessors will generate appropriate KVO notifications for free. (UPDATE 2008-11-10: If you’re targeting Leopard, declare and use (i.e., self.foo = bar
) Obj-C 2 properties. Exception: Not in your init
and dealloc
methods, and that goes for regular accessors as well.)
Some are for arrays, some are for sets, some are only for mutable properties, and some are for all keys.
validate%s:error:
%sForKeyPath:
_%sForKeyPath:
get%s
is%s
_get%s
countOf%s
objectIn%sAtIndex:
%sAtIndexes:
get%s:range:
enumeratorOf%s
memberOf%s:
_is%s
set%s:
_set%s:
getPrimitive%s
primitive%s
setPrimitive%s:
add%sObject:
remove%s:
remove%sObject:
add%s:
intersect%s:
insertObject:in%sAtIndex:
insert%s:atIndexes:
removeObjectFrom%sAtIndex:
remove%sAtIndexes:
replaceObjectIn%sAtIndex:withObject:
replace%sAtIndexes:with%s:
Source: strings /S/L/F/Foundation.framework/Foundation.
Note that NSArrayController will not call the finer-grained array methods (e.g., insertObject:in%sAtIndex:
) if you provide the basic get and set methods (%s
and set%s:
).
November 26th, 2008 at 01:21:06
Can you elaborate on your “Exception:” part? What do you mean exactly and what are the reasons behind the exception? Thanks! Btw. I found “How to work with a bound-to array” extremely useful.
November 26th, 2008 at 01:51:44
Petteri Kammpuri: Don’t use property-access expressions in
init
anddealloc
methods, because the property access will call your accessors.In the former case, you may not have completely initialized the object yet; in the latter case, you may have partially destructed it. If you have custom accessors that reply on other properties of your object, this may be a problem. And you can’t say with 100% confidence that you will never, ever make a custom accessor for that property.
So don’t do it.
init
methods (includinginitWithSomethingElse:
methods), always assign the retained or copied object directly to the instance variable (in other words,myObject = [newObject retain]
, notself.myObject = newObject
).dealloc
methods, always get the object directly from the instance variable before you sendrelease
to it (in other words,[myObject release]
, not[self.myObject release]
).November 26th, 2008 at 05:03:52
Okay, thanks. The
init
case was what intrigued me the most. It’s probably easy to get right in the class you’re writing, but subclasses could break those assumptions, and using accessors might invoke subclass code when the subclass hasn’t been inited. That’s a good reason to stay away from accessors.I haven’t used accessors in
dealloc
methods, but I haven’t been as strict withinit
s. I’ll be from now on.