Question

I have a class that builds a request based on a few passed in variables. The class also has all the delegate methods to receive the data and stores it in a property for the calling class to retrieve.

When the class initializes it creates a connection and then returns itself:

NSURLConnection *connection;
if (self = [super init]) {
    self.delegate = theDelegate;
    ...some code here...
    connection = [[NSURLConnection alloc] initWithRequest:theRequest  delegate:self  startImmediately:YES];
}
return self;

So I can't release it normally and if I autorelease it crashes. Is it the job of the calling class to release? And if so does just releasing the initilised object also release connection or do you have to release it specifically? If so how would you?

Thanks

Was it helpful?

Solution

Make connection an instance variable and release it on-demand. The question "who" should release the object depends strictly on your object semantics and hierarchy.

OTHER TIPS

Why are you opening an NSURLConnection within a constructor?

Typically, your constructor shouldn't perform this type of work. If the connection is associated to the object, I would make connection a property of the object and [connection release]; within the object's dealloc method.

Remember that you shouldn't place all your faith in Clang. It can and does report false negatives and false positives.

Clang is getting better every day, but it still in its infancy right now. It's great that it's integrated with Xcode so nicely, but just keep in mind that it does have some flaws.

In this case, it depends on the scope of the variable you're storing the connection object in. If it's declared as an instance variable, then it should be ok, as long as you release it in dealloc or at some other point when you're done with it.

If, like you've posted in your question, the declaration of connection is local to your init method, then Clang is correctly reporting a leak. You should make connection an instance variable or property and ensure you release it in dealloc or when you're finished with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top