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);
}
EDIT: To extend this a bit more, perhaps it's essential to include that MyObj is using NSURLConnection.
MyObj:
@implementation MyObj
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[self.delegate callbackMethodFromMyObj:@"a string"];
}
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?
I have updated this post to include the fact that I'm using NSURLConnection, so threading is involved here.
If I were to release *myObj then it would be released before NSURLConnection has a chance to call - (void)connectionDidFinishLoading:(NSURLConnection *)connection
As I see it, and from the reply below, it seems like it's essential to pass *myObj along as a parameter in the callback, thus releasing it inside - (void)callbackMethodFromMyObj:(NSString *)message
and changing the method signature, resulting in the following method:
- (void)callbackMethodFromMyObj:(NSString *)message withMyObj:(MyObj *)sender
{
// do things
[myObj release];
}