On 20/05/2009, at 11:11 PM, Jerry Krinock wrote:

I still say, use a delegate. Think of a delegate as a general- purpose ivar. Lots of Cocoa classes have delegates that I don't always use. A delegate is not ugly. Just hold your nose if necessary, add a delegate and move on.


I'm coming around to this view. At least a delegate is not committed to any particular functionality, so adding it could be useful in a general way, even if it is unused by the framework.

Given that then, and the idea that I'm using it to effectively extend the ivars of an object, I'm also considering the wisdom of the following (feel free to comment/criticise):

Object A supports NSCoding and can be archived as usual, as well as NSCopying. So that the delegate can effectively extend A, the following informal protocol is proposed for direct support by A.


@interface NSObject (MyObjectDelegate)

- (void) object:(MyObject*) obj willBeEncodedWithCoder:(NSCoder*) coder;
- (void) object:(MyObject*) obj wasInitedWithCoder:(NSCoder*) coder;
- (void) object:(MyObject*) obj didMakeCopy:(MyObject*) copy withZone: (NSZone*) aZone;
- (void) objectWillBeDeallocated:(MyObject*) obj;


@end

Then, in A's -encodeWithCoder: I call the delegate's first method if it responds to it, followed by a conditional encoding of the delegate. In -initWithCoder:, I decode the delegate, then at the end call the second method, if the delegate responds. Thus, if the delegate is extending A, archiving A gives it a proper chance to store itself in the archive on A's behalf. If the delegate isn't extending A, it doesn't get these messages, though it will be conditionally encoded anyway.

While the delegate could be simply unconditionally archived, it's unsafe to assume that it should be, since A has no idea what it is. That's why it needs to send it a special message so it can archive itself. If it isn't archived, -initWithCoder: wouldn't have a delegate to send the message to so the dearchiving would be incomplete. I'm unsure about the wisdom of this, even though in my specific case I know that the delegate will be a small extension object.

Copying and deallocation are straightforward, I think.


--Graham


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to