Understanding Memory Management in Objective-C

I have the following code that works fine, but I'm not sure if I understood some concepts of memory management correctly:

#import "mapPoint.h"

@implementation mapPoint
@synthesize coordinate, title, subtitle;

-(id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t {
    [super init];
    coordinate = c;
    [self setTitle:t];
    // Set date as subtitle
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    NSString *myDate = [dateFormatter stringFromDate:[NSDate date]];
    [self setSubtitle:myDate];
    [dateFormatter release];
    // Look for city and state; when found, set it in subtitle, replacing date
    geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:c];
    [geocoder setDelegate:self];
    [geocoder start];
    return self;
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    NSLog(@"%@", error);
}
-(void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    [self setSubtitle:[NSString stringWithFormat:@"City: %@, State: %@", [placemark locality], [placemark administrativeArea]]];
}
-(void)dealloc {
    [title release];
    [subtitle release];
    [geocoder release];
    [super dealloc]; 
}

@end 
  • When I created the geocoder object using the method alloc, I have to free it (done in dealloc). Correctly?
  • An reverseGeocoder:didFindPlacemarkNSString is created in the method using the convenience method stringWithFormat. Since I have not used alloc, I am not responsible for releasing it (I assume this method uses autorelease). It is right?
  • placemark NSStrings, locality administrativeArea. , , . , , mapPoint, , , , , autorelease. subtitle retain. , NSString, , ?

, ... .

+3
4
  • - ivar ? . , , , ( ivar nil) , .
  • , . , "" "", , .
  • . , setSubtitle: , @synthesize , setSubtitle:.

Edit:

, 3. [placemark locality] [placemark administrativeArea] NSString stringWithFormat, , , stringWithFormat. , , , , setSubtitle: .

+1

- - Cocoa . , : . .: -)

+1
  • , dealloc
  • , NSString
  • , NSStrings.

, "" ". , , " ".

+1

, :

  • [super init] self, :

    - init
    {
        self = [super init];
        if (!self) return nil;
    
        // do initialisation
    
        return self;
    }
    

    , , [super init], ( ) self.

  • , - , , setTitle: setSubtitle: . , KVO, .

+1

Source: https://habr.com/ru/post/1796722/


All Articles