A 有一个对象(secondObject),它是 NSObject 的子类的一个实例,并且在 secondObject 中,我想获得对实例化 secondObject 的对象(firstObject)的引用。
例子:
在 FirstObject.m(UIViewController 的子类)中
SecondObject *secondObject = [[SecondObject alloc] init];
在 SecondObject.m 中
@implementation SecondObject
- (id) init {
self = [super init];
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
我正在寻找类似于 viewControllers 的 .parentViewController 属性的东西
我一直在研究 KeyValueCoding,但一直没能找到解决方案。
我实现的解决方法是在 secondObject.m 中创建一个 initWithParent:(id)parent 方法,然后在实例化时传递 self 。
在 SecondObject.m 中
@interface SecondObject ()
@property id parent;
@end
@implementation SecondObject
- (id) initWithParent:(id)parent {
self = [super init];
self.parent = parent;
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
然后实例化fisrtObject.m中的对象如下
SecondObject *secondObject = [[SecondObject alloc] initWithParent:self];
有没有更直接的方法来做到这一点?
Rgds....恩里克