Re: private redeclaration of an instance variable
Re: private redeclaration of an instance variable
- Subject: Re: private redeclaration of an instance variable
- From: Jens Alfke <email@hidden>
- Date: Sat, 29 Jun 2013 10:55:15 -0700
On Jun 29, 2013, at 10:23 AM, Matt Neuburg <email@hidden> wrote:
> Am I reading this right? It's permitted to override an inherited instance variable, but only if you do so privately? m.
First, you can’t override an instance variable; they aren’t dynamic enough. An ivar is like a struct field, it compiles into a fixed offset from a base pointer*. There’s nothing a subclass can do that affects the way its superclass gets and sets its ivars.
This is just a parsing issue. If an ivar is declared in a class’s public interface, it’s in scope in any method of that class or a subclass. So if a subclass declares an ivar with the same name, you now have a conflict and the parser won't know which one you’re referring to, so it won’t let you do that.
But if the base class’s ivars are declared in the implementation, then the parser doesn’t see them at all and has no idea what they’re called, so it doesn’t mind you declaring one with the same name (it can’t even tell that’s what you’re doing.)
This is a big improvement. It used to be possible [though I don’t know if it ever occurred IRL] to add an instance variable to a class, like in an OS update, and accidentally break the compilation of a subclass that already had an ivar with that name. (It wouldn’t cause any runtime problems for already-compiled code, though.) This is why Apple used to discourage developers from using underscore prefixes on ivar names: because that’s the convention they use in their own classes.
—Jens
* That ‘base pointer’ used to be ‘self’ in the old runtime, but that led to the infamous fragile-base-class problem. Nowadays it’s a pointer to the start of that class’s instance data, whose offset from ‘self’ is fixed at runtime, determined dynamically when the class is loaded. (TMI, sorry!)
_______________________________________________
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