Search code examples
objective-cobjectparentkvc

How to get a reference to the object that instantiated a second object in Objective-C?


A have an object (secondObject) that is an instance of a subclass of NSObject, and within secondObject, I want to get a reference to the object where secondObject was instantiated (firstObject).

Example:

In FirstObject.m (subclass of UIViewController)

    SecondObject *secondObject = [[SecondObject alloc] init];

in SecondObject.m

    @implementation SecondObject
    - (id) init {
        self = [super init];
        NSLog(@"Parent object is of class: %@", [self.parent class]);
    return self;
    }
    @end

I was looking for something similar to the .parentViewController property of viewControllers

I have been researching KeyValueCoding, but haven't been able to find a solution.

The workaround I implemented, was to create a initWithParent:(id)parent method in secondObject.m and then pass self at the instantiation.

in 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

And then instantiate the object in the fisrtObject.m as follows

    SecondObject *secondObject = [[SecondObject alloc] initWithParent:self];

Is there a more straightforward way to do it?

Rgds.... enrique


Solution

  • Objects do not have any sort of pointer to the object that created it.

    Your initWithParent: method will work, but you may want to think about why your object needs to know its creator and if there isn't a better way to accomplish whatever you're trying to accomplish.

    Also, you're probably going to want to make the parent property a weak property or you're going to end up creating retain cycles all over the place.