I would like to have a method along the lines of
setData:(SomeClassName *)data inPosition:(NSInteger)position
and in the implementation, check for nil as position. The idea is that if the position is provided, I will use it, and if not, I will allocate it automatically.
The problem is I can’t pass either NULL or nil into this without a compiler warning.
I believe I have seen this pattern elsewhere (optional parameters). I think it might have been related to an NSIndexPath.
Should I use an NSNumber as a wrapper? or is there some other secret?
As an aside, I considered using separate methods – setData: and setData:inPosition:. But the problem is that ‘data’ is a core data created attribute, not a regular ivar, so when I actually want to set the value I would have to remember to send all the KVO messages. For example, inside setData:withPosition, I can’t call the standard setData: – it would overwrite any work I did with the position.
Would also be interested in knowing which is the ‘better’ solution of these two.
@Justin’s approach is generally the most appropriate. However, to your question about
setData:and KVO, there are several things to note:KVO notifications are sent automatically as long as the method is named
setFoo:. Even if you overridesetFoo:, KVO will wrap your implementation with the correct KVO notification calls for the property. This is very likely the most magical thing in Cocoa. (I used to be certain it was the most magical thing, but I’m starting to wonder about block variable scoping, and especially how blocks are moved from the stack to the heap; that may be more magical.)If you need to set a Core Data attribute directly, bypassing KVO and every other piece of possible magic, you can use the primitive accessor.
setPrimitiveData:is the underlying method thatsetData:uses to set the property. You should not override the primitive accessors.@Justin appears to have deleted his answer. The typical solution here would be to declare
setData:andsetData:inPosition:(btw, as a reader, I have no idea what “inPosition” means. I hope that it makes sense in context).setData:would callsetData:inPosition:applying whatever is necessary to figure out “position.”