Search code examples
iphoneiosobjective-cipadxcode4

Memory Management Confusion Objective C


Question 1

Place *place = [[[Place alloc] initwithCoordinate:location anotationType:CSMapAnnotationTypeStart] autorealease];
place.name = name;
place.description = description;
place.strUniqueIdentity = uniqueIdentity;
NSLog(@"Unique identity %@",uniqueIdentity);

PlaceMark *marker = [[PlaceMark alloc] initWithPlace:place annotationType:MapAnnotationTypePin];
return [marker autorelease];

When i analyze the code in xcode 4.6.2 then it is showing 'Object sent -autorelease too many times' at second last line. I can't understand why it is showing that.

Screenshot 1

Question 2:

return [[[OAProblem alloc] initWithResponseBody:response] autorelease];

And in this line it is showing "Potential leak of an object stored in 'self'".

Screenshot 2


Solution

  • Answer of first part of my question is the small 'w' in the initialization method

    -initwithCoordinate: anotationType:
    

    I have to use capital 'W' according to Cocoa naming conventions.

    I replaced the initialization method with

    -initWithCoordinate: anotationType:
    

    Answer of second part of my question is to add a [self release] in both the failure paths

    Xcode is being very unhelpful in it's analyser warning about OAProblem.c.

    The code that's actually the problem is up in the init methods. The warning (in this case) means "an init method is returning nil without releasing the object allocated by alloc". The fix is to add a [self release] in both the failure paths:

    - (id)initWithProblem:(NSString *) aProblem
    {
        NSUInteger idx = [[OAProblem validProblems] indexOfObject:aProblem];
        if (idx == NSNotFound) {
            [self release]; // <-- Add this line to fix the warning
            return nil;
        }
    
        return [self initWithPointer: [[OAProblem validProblems] objectAtIndex:idx]];
    }
    

    and the same for initWithResponseBody.