【发布时间】:2014-02-07 03:48:56
【问题描述】:
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....恩里克
【问题讨论】:
-
你想出的是正确的方法。或者在调用
init之后设置属性。两者都可以。
标签: objective-c object parent kvc