1

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....恩里克

4

2 回答 2

2

对象没有任何指向创建它的对象的指针。

您的 initWithParent: 方法将起作用,但您可能想考虑一下为什么您的对象需要了解它的创建者,以及是否没有更好的方法来完成您想要完成的任何事情。

此外,您可能希望将父属性设为弱属性,或者您最终会在各处创建保留周期。

于 2014-02-07T03:55:47.980 回答
1

应该是_parent = parent;那个init方法吧,除此之外,也没什么大不了的。据我所知,做与此类似的事情实际上很常见(initWithDelegate:等)

然而...

编写一个类符合的 a 可能是明智的@protocolparent而不是只采用一个id,您需要一个符合协议的对象。

于 2014-02-07T03:55:57.527 回答