Challenge: Annotation Extras


#1

So, I accepted the challenge, and my annotations include the date. My code:

[code]-(id)initWithCoordinate:(CLLocationCoordinate2D)c2d title:(NSString *)t {
[super init];
coordinate = c2d;

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@" MM-dd-yyyy"];

NSString *theDate = [dateFormat stringFromDate:[[NSDate alloc] init]];
NSMutableString *texty = [[NSMutableString alloc] init];
[texty setString:t];
[texty appendString:theDate];

[self setTitle:texty];

[dateFormat release];
[texty release];

return self;

}
[/code]

I’m happy that it works, but am looking for stylistic feedback.

In the above, why does theDate not need to be released (according to the Xcode analyzer)?

Also, in Java, you can bang together all sorts of constructors and pass them values and come out with what you need and all of the temporary variables and structures are then cleared up. So to my way of thinking, everything from “NSDateFormatter…” to “…setTitle:texty” should be bunged together into one statement. Is this possible in Objective C? Seems like many of the initializers return a void that needs to be ignored, or that I’m not syntaxing them correctly.

Thompson


#2

Hi,

I’m not sure why the analyser isn’t finding it, but the line - NSString *theDate = [dateFormat stringFromDate:[[NSDate alloc] init]];
is leaking the alloc’d NSDate.

you could use - NSString *theDate = [dateFormat stringFromDate: [[[NSDate alloc] init] autorelease]];

or [NSDate date] which is autoreleased for you.

You can join methods together - [[[NSDate alloc] init] autorelease] is a good example but iOS doesn’t have a garbage collector so there is no automatic cleanup. Also Objective C / Cocoa is quite verbose and I personally find it easier to understand code that doesn’t overdo it.

Gareth


#3

I am new to memory management. I went through the chapter in the book, but when I looked at the code example … and then saw your post (Gareth) I thought to myself … I would never have seen a memory leak in that code. Maybe this will just take time to get used to.

Are there certain things that stand out and scream “I’M LEAKING VALUABLE MEMORY!!!” when looking at someone’s code (or my own)?

Any suggestions would be helpful.


#4

whenever you allocate memory you have to release it. so if you have an alloc command there has to be a release for it :slight_smile: