在可可中访问父类的对象 [英] Accessing objects of parent class in cocoa
问题描述
我有一个主要的AppDelegate类(MacOS开发的,不是iOS),用于通过以下方式初始化子类:
I have a main AppDelegate class (MacOS development, not iOS) initiating a child class with
myChildClassObject=[[myChildClass alloc]init:self];
因此,我确实将父引用发送到子类. 但是,如何从子类访问父类的对象? 我尝试过
So I do send the parent reference to the child class. However how can I access an object of my parent class from my child class ? I tried with
parent.myObject
但找不到它.
我的父类的定义如下:
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
NSView *myObject;
}
@property (nonatomic, readwrite, retain) NSView *myObject;
@end
我的子类的定义如下:
@interface Gfx
{
}
谢谢.
推荐答案
这里有几件事:
1)您可以通过此行轻松获得对应用程序委托的引用:
1) You can easily get a reference to an application's delegate via this line:
AppDelegate * appDelegate = [[NSApplication sharedApplication] delegate];
2)如果要在孩子中存储对父母的引用,则可以执行以下操作:
2) If you want to store a reference to the parent in the child, you can do something like this:
向孩子的.h @interface文件添加一个如下所示的属性:
add a property to your child's .h @interface file that looks like this:
@property (retain) id parent;
然后,在您的父类中,并且在实例化子对象之后,您可以执行以下操作:
Then, in your parent class and right after instantiating your child object, you can do:
ChildObject * child = [[ChildObject alloc] init];
child.parent = self;
您可以通过以下方式从子项中引用父类:
And you can refer to the parent class from within the child via:
self.parent;
这篇关于在可可中访问父类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!