Re: ObjC question
Re: ObjC question
- Subject: Re: ObjC question
- From: Kevin Brock <email@hidden>
- Date: Sat, 10 Apr 2010 16:41:55 -0700
On Apr 10, 2010, at 2:38 PM, Tony Romano wrote:
> Using the sample below, how do I get the instance of the class in which I am contained WITHOUT passing it as a parameter or using hacky sizeof tricks in the method Foo:method? Thanks people! If this is not the correct alias for this type of question, apologizes in advance.
You do need to pass it as a parameter. If you look at how Interface Builder connects with code, actions called by, for example, buttons include a 'sender' parameter:
- (void) myAction:(id)sender;
This is done all over the place...
You call the method:
[f method:self];
and you're done. I'm not clear on why you don't want to pass it as a parameter. If that's really a firm restriction you'll need to explain why in order for anyone to answer the question adequately.
BTW, when you say (in a later message) that an instance of f is contained in one instance of Bar, that's not a language restriction. It's just how you designed it. If it's an explicit part of the design it's OK to write code that knows about that...
try this. I've left out anything related to reference counting, but I think it's basically right:
@interface Foo : NSObject
{
id containerClass:
}
- (id) initWithContainer:(id)container;
@end
@implementation Foo
- (id) initWithContainer:(id)container
{
self = [super init];
if(self)
containerClass = container;
return self;
}
@end
@interface Bar : NSObject
{
Foo* f;
}
@end
@implementation Bar
@implementation Bar
- (id) init
{
f = [[Foo alloc] initWithContainer:self];
}
@end
Kevin
_______________________________________________
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