The problem with +alloc
is that it retains its result, which is why it must be balanced with a call to -release
or -autorelease
later on. To avoid having to type that out over and over every time a class is used, API designers commonly create what's called a convenience constructor or convenience method. +URLWithString:
is one of them, and internally it looks like this:
+ (id)URLWithString: (NSString *)str {
return [[[self alloc] initWithString: str] autorelease];
}
So +alloc
is getting called for you, and so is -autorelease
.
Background
There are two broad kinds of methods in Objective-C: class methods and instance methods. Class methods are sent to a class itself and do not require the creation of an instance of that class. Instance methods are sent to an instance and can access the memory that instance occupies. Class methods start with +
; instance methods with -
.
+alloc
is a class method. It's not a magical one with particular object-creating powers. All it does internally is something like:
+ (id)alloc {
id result = malloc(class_getInstanceSize(self));
if (result) {
memset(result, 0, class_getInstanceSize(self));
result->isa = self;
result->retainCount = 1;
}
return result;
}
(It's actually a little more complicated than that but it should suffice here.) Note that +alloc
is defined to be part of NSObject
, not part of all objects. Cocoa memory management, with +alloc
, -init
, -retain
, -release
, etc. is not always part of Objective-C, and objects can be created that don't use it.
You can actually create instances of a class without calling +alloc
if you know the right incantations. I wouldn't recommend it.