Re: private redeclaration of an instance variable
On Jun 29, 2013, at 7:48 PM, David Duncan <david.duncan@apple.com> wrote:
On Jun 29, 2013, at 11:18 AM, Matt Neuburg <matt@tidbits.com> wrote:
On Jun 29, 2013, at 10:55 AM, Jens Alfke <jens@mooseyard.com> wrote:
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.
That is what I would have thought, but that is exactly what I appear to be doing. That's what I'm finding so odd.
* MyClass, the superclass, defines "thing" as an int, in public (in its interface section in its header file).
* MyClass2, the subclass, defines "thing" as an NSString*, in private (in its implementation section).
I would have expected a conflict. Instead, the compiler seems quite happy, provided any mention of self->thing in MyClass2 is an NSString.
Of course it's possible that I've just confused the heck out of myself and my experiment doesn't show what I think it shows. But try it; I think you'll find that what I'm saying is true. m.
Think of it like scope. Your class's @implementation defines a more limited scope than the class's @interface or its superclass's @interface. When you add a new ivar in the @implementation block, it hides the ivar from the super class, just as what happens when you define a local variable with the same name as an enclosing scope.
What can get confusing is that if you type case to the super class you can still access the hidden ivar. In general I would avoid this (as I would avoid declaring ivars in a public interface).
Fascinating, Captain! I really like this "scope" analogy. In my defence, I was declaring the ivar in the public interface only because I wanted to experiment with the subclass's access to the ivar; it can't see the ivar at all if it isn't declared in the superclass's public interface (or in a mutually imported header file, which is what I usually do in these situations). I hadn't gotten around to trying the typecasting trick yet. :))) Thx as usual - m. -- matt neuburg, phd = matt@tidbits.com, http://www.apeth.net/matt/ pantes anthropoi tou eidenai oregontai phusei Programming iOS 6! http://shop.oreilly.com/product/0636920029717.do RubyFrontier! http://www.apeth.com/RubyFrontierDocs/default.html TidBITS, Mac news and reviews since 1990, http://www.tidbits.com _______________________________________________ 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: https://lists.apple.com/mailman/options/cocoa-dev/site_archiver%40lists.appl... This email sent to site_archiver@lists.apple.com
participants (1)
-
Matt Neuburg