eharo2
eharo2

Reputation: 2642

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

Upvotes: 1

Views: 132

Answers (2)

nhgrif
nhgrif

Reputation: 62062

It should probably be _parent = parent; in that init method, but other than that, there's not much wrong with this. It's actually pretty common as far as I know to do things similar to this (initWithDelegate: etc)

However...

It would probably be wise to write a @protocol that the parent class conforms to, and rather than taking just an id, you require an object that conforms to the protocol.

Upvotes: 1

Kris Flesner
Kris Flesner

Reputation: 428

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.

Upvotes: 2

Related Questions