Reputation: 3317
In one of my functions, I have a while loop with a certain case where it may need to temporarily create an object. My code looks like this:
while(c < end){
if(specialCase){
Object *myObject = [Object alloc];
//do stuff with myObject
//I tried [myObject dealloc] here, but it crashed when this method was called.
}
c++;
}
The code works fine as is but I am worried about memory leaks. I would like to know if and how I should dealloc myObject.
Upvotes: 0
Views: 213
Reputation: 993
You could probably try using a Smart Pointer. This should take care of garbage collection and any exception handling. Also, Boost libraries can be ported for ios.
Upvotes: 0
Reputation: 963
try this
while(c < end){
if(specialCase){
Object *myObject = [[Object alloc] autorelease];
//do stuff with myObject
//I tried [myObject dealloc] here, but it crashed when this method was called.
}
c++;
}
Upvotes: 0
Reputation: 31722
you should not call dealloc
method directly, Calling release
on the object which are either alloced
or retain
will call dealloc
implicity ,if the retain count for that object meet with condition put by iOS system (Usually if the retain count is ZERO for the object).
Read the apple documentation of dealloc
method in NSObject class and also go through the Memory Management Programming Guide for objective-C
Upvotes: 1
Reputation: 771
You NEVER call Dealloc directly.
you call Release and when retain count reaches 0 dealloc will be called on object.
Upvotes: 5