Re: Cocoa class extension best practice
Re: Cocoa class extension best practice
- Subject: Re: Cocoa class extension best practice
- From: Uli Kusterer <email@hidden>
- Date: Wed, 16 Oct 2013 20:46:39 +0200
On 16 Oct 2013, at 18:57, Steve Mills <email@hidden> wrote:
> So at this point, let's finish this thread by going back to my original question. Is it OK to use the private instance variable _itemArray in NSMenu since the methods we've added are *extensions* of NSMenu and not a subclass? They simply iterate over the array and ask each item for its tag and call the same method on submenus. Below is the way it is now, with [self itemArray] being called, which seems inefficient because it creates an immutable copy of the array. If NSMenu were my own class, I'd definitely use the instance variable for this sort of routine.
Nope. That would be violating encapsulation. Apple give no guarantees regarding instance variables, hence @private. Don't use them. They're only part of the API contract insofar as the Mac's 32-bit runtime requires the ivar section to remain the same size in bytes to stay binary compatible (i.e. every Application written against 10.9 would fail if 10.10 suddenly decided to take out this instance variable).
However, Apple are free to change the name and number of ivars used, or replace one ivar with two of the same size, or change their type. So in 10.10 _itemArray could be changed to be a void* that gets malloced manually and contains a linked list of Apple's own making that might not even be an ObjC object. Since that pointer is the same size as any other pointer, the class stays binary compatible for all users (and your category) as long as you only use the methods, and the -itemArray method somehow builds an NSArray from that internal linked list.
Your app that directly accesses the _itemArray ivar would then break.
Also, note that _itemArray is typedefed as an 'id'. You have *no* idea whether it is an NSArray. Even if you check whether it is for one particular menu at the moment, they might be putting another object into this ivar under certain circumstances.
Apple have done things like replace ivars in the past. E.g. I'm pretty sure the _extra ivar in NSMenu used to be something else and now points to another object that contains additional ivars that have been added since NSMenu was introduced. They can't make it larger under the old 32-bit Mac runtime, after all.
-- Uli Kusterer
"The Witnesses of TeachText are everywhere..."
_______________________________________________
Cocoa-dev mailing list (email@hidden)
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:
This email sent to email@hidden