如何获取对Objective-C中实例化第二个对象的对象的引用?
A有一个对象(secondObject),它是NSObject子类的一个实例,在secondObject中,我想获得对实例化secondObject的对象(firstObject)的引用 例如: 在FirstObject.m(UIViewController的子类)中 在SecondObject.m中如何获取对Objective-C中实例化第二个对象的对象的引用?,objective-c,object,parent,kvc,Objective C,Object,Parent,Kvc,A有一个对象(secondObject),它是NSObject子类的一个实例,在secondObject中,我想获得对实例化secondObject的对象(firstObject)的引用 例如: 在FirstObject.m(UIViewController的子类)中 在SecondObject.m中 @implementation SecondObject - (id) init { self = [super init]; NSLog(@"Pa
@implementation SecondObject
- (id) init {
self = [super init];
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
@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
我正在寻找类似ViewController的.parentViewController属性的内容
我一直在研究KeyValueCoding,但还没有找到解决方案
我实现的解决方法是在secondObject.m中创建initWithParent:(id)parent方法,然后在实例化时传递self
在SecondObject.m中
@implementation SecondObject
- (id) init {
self = [super init];
NSLog(@"Parent object is of class: %@", [self.parent class]);
return self;
}
@end
@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
然后在FirstObject.m中实例化对象,如下所示
SecondObject *secondObject = [[SecondObject alloc] initWithParent:self];
有没有更直接的方法
Rgds。。。。enrique对象没有指向创建它的对象的任何类型的指针 您的initWithParent:方法可以工作,但您可能需要考虑为什么您的对象需要知道其创建者,以及是否有更好的方法来完成您试图完成的任务
此外,您可能希望将父属性设置为弱属性,或者最终在所有位置创建保留循环。它可能应该是
\u parent=parent
在这个init
方法中,但除此之外,这个方法没有太大的错误。据我所知,做类似的事情是很常见的(initWithDelegate:
etc)
然而
编写父类所遵循的
@协议
可能是明智的,而不是只获取id
,您需要一个符合协议的对象。您想到的是正确的方法。或者在调用init
后设置属性。这两种方法都有效。这是正确的答案。委托是一种非常重要的设计模式。你可以在这里读到:Thx nhgrif。。。我在项目的另一部分实现了@协议。我将此视为一个挑战,因为我想做的是在概念上类似于将id委托从父类移动到实例化的类,以便访问委托方法和属性。这是一个项目的一部分,该项目使用CoreText(用于多篇文章-页面-列),包括使用收缩手势的动态字体大小调整,并且解析器和页面列生成器位于单独的类分支中。