Creating and releasing objects in the same method, while using self as delegate

Posted by user200341 on Stack Overflow See other posts from Stack Overflow or by user200341
Published on 2010-06-18T11:30:47Z Indexed on 2010/06/18 11:33 UTC
Read the original article Hit count: 194

In objective-c you are responsible for releasing objects you allocate, but what happens when you allocate an object in a method, assign self as the objects delegate, and then release the object.

The callbacks from the newly created (and released) object fails at this point, or rather, doesn't happen.

- (void)doSomething
{
    MyObj *myObj = [[MyObj alloc] init];
    myObj.delegate = self;
    [myObj performOperation];
    [myObj release];
}

- (void)callbackMethodFromMyObj:(NSString *)message
{
    NSLog(message);
}

I can't release the object until the callback has occurred, and I can't avoid releasing the object in the same method that creates it (because it exists outside the scope).

One way of doing it would be to pass the object along in the call-back and release it in the callback, but is this the right way to go about this?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about memory-management