An introduction to Objective-C
thinkvitamin.com
thinkvitamin.com
- (id) initWithTitle: (NSString *)aTitle{
self = [super init];
if (self) {
title = aTitle;
}
return self;
}
aTitle isn't retained (and no, he's not using ARC). This is such an obvious, basic mistake that I have no faith in the author at this point.Here's another error:
For example, this is valid code:
NSObject obj = [Book createBookWithTitle:@"A Brave New World"];
That's not true. It's missing the pointer (NSObject *, not NSObject). Furthermore it's otherwise syntactically valid but comes dangerously close to violating Cocoa best practices for memory management. The method (which returns an autoreleased result in their examples) should be named "bookWithTitle:".Putting "create" in the name doesn't actually violate the memory management rules (in Cocoa, only methods that have alloc, new, copy, or mutableCopy return owning references). But it will cause confusion with the Create Rule from Core Foundation:
Object-creation functions [have] “Create” embedded in the name...
it is your responsibility to relinquish ownership (using CFRelease) when you have finished with it
Sure, Core Foundation is not Cocoa. But since it's often intermixed, sometimes explicitly with toll-free bridging, boy are people going to be confused someday!However, the tutorial is now #3 on the front page.
title = aTitle;
he should say self.title instead to avoid memory issues.
I don't really like the property dot syntax though, I always use the `setProperty:` form for consistency (is it a struct or an object? why is the = operator sending an Obj-C message?)