Re: @protected variable access
Re: @protected variable access
- Subject: Re: @protected variable access
- From: Matt Neuburg <email@hidden>
- Date: Tue, 14 Sep 2004 11:42:18 -0700
On Mon, 13 Sep 2004 14:39:09 -0500, Tim Hart <email@hidden> said:
>
>On Sep 12, 2004, at 12:38 PM, Matt Neuburg wrote:
>
>> On Sat, 11 Sep 2004 15:30:26 -0500, Tim Hart <email@hidden> said:
>>> Assume the following:
>>>
>>> @interface Foo :NSObject
>>> {
>>> @protected
>>> int i;
>>> }
>>>
>>> @end
>>>
>>> @interface Bar : Foo
>>>
>>> -(id) initWithFoo:(Foo*)foo;
>>>
>>> @end
>>>
>>>
>>> So we have Bar as a subclass of Foo, but also initializable with an
>>> instance of Foo - a quasi-copy initializer.
>>>
>>> I was under the impression that initWithFoo could legally do the
>>> following:
>>>
>>> @implementation Bar
>>>
>>> -(id) initWithFo:(Foo*)foo
>>> {
>>> i = foo->i;//legal access to a protected member.
>>> }
>>> @end
>>
>> It works if you cast foo down to a Bar*. I had the same problem a
>> couple of
>> years ago, and was straightened out by Mike Shields:
>>
>> <http://www.cocoabuilder.com/archive/message/2002/10/24/71216>
>
>Thanks. In my case, I'm a little uncomfortable with that approach. The
>variable would actually be an instance of Foo. So while everything
>would be fine if I limited access of my 'false Bar' to Foo ivars, I'd
>get some really wacky runtime behavior if I forgot that rule and tried
>to access any 'Bar' ivars.
I don't know that I see this as a problem. I was not suggesting that you
downcast permanently - just for that one statement where you want to access
a protected superclass ivar.
>I've taken a completely different approach to my problem, but in your
>case, this would also work, and *might* be safer. I say might because I
>don't know the specifics of your issue...:
>
>typedef struct{
> @defs(Foo)
>}FooStruct;
>
>-(id)initWithFoo:(Foo*)foo
>{
> i = ((FooStruct*)foo)->i;
>}
But that works for private ivars too, from any class (not just a subclass),
so essentially you're just throwing public / private / protected out the
window. If you're going to do that, why not declare all your ivars public
and just program by contract? Or to put it another way, if this counts as a
solution for you, why bother using @protected to begin with? m.
--
matt neuburg, phd = email@hidden, <http://www.tidbits.com/matt/>
A fool + a tool + an autorelease pool = cool!
AppleScript: the Definitive Guide
<http://www.amazon.com/exec/obidos/ASIN/0596005571/somethingsbymatt>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden