I have a connection class that uses NSURLConnection to connect to the server. While in main class I call a class method of this class, the class method then allocates instance of itself and when the delegate ConnectionDidFinish is received, I release same class from within. Is this approach correct or this will lead to some problem.
Main Class :
[ConnectionClass connectToServer];
Connection Class :
@implementation ConnectionClass
+(void)connectToServer{
connectionClass = [[ConnectionClass alloc] init];
[connectionClass createConnection];
}
-(void)createConnection{
NSURLConnection *connection = [[NSURLConnection alloc] initWithDelegate:self];
// create asynchronous connection
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self release];
}
@end
Is it good to release self within its own method ?
What if I do it something this way;
Main Class :
[connectionClass setDelegate:self];
[connectionClass connectToServer];
Connection Class :
@implementation ConnectionClass
-(void)connectToServer{
[connectionClass createConnection];
}
-(void)createConnection{
NSURLConnection *connection = [[NSURLConnection alloc] initWithDelegate:self];
// create asynchronous connection
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.delegate finishedConnection:self]; // added delegate and then called to the main class and pass the self object for main to release it
}
@end
And in the main class delegate we, release the object,
-(void)finishedConnection:(ConnectionClass*)connection
{
[connection release];
}
IS there any problem in releasing the object this way ?
I would do this:
That way the
ConnectionClassobject is self retaining, and you’re not putting the retain/release responsibility in different places of code, that are not tightly related.Edit: As Rabskatran points out, if you’re just learning about retain/release, then this is not the optimal solution.
Your second example with the delegate is better. I’d let the
connectionClassobject be an instance variable, so you can message the connection object to cancel the operation when the main class (which would be the connection’s delegate) gets deallocated.