views:

210

answers:

1

Is there a good reason why I should not do something like this? Example:

I have a class MyClass. In there I have this implementation:

- (id)copyWithZone:(NSZone*)zone {
    MyClass *copy = [[MyClass allocWithZone:zone] init];
    copy.someproperty = [[self.someproperty copy] autorelease];
    return copy;
}

Instead of that, I found a snippet that looks like this:

- (id)copyWithZone:(NSZone*)zone {
    MyClass *copy = [[[self class] allocWithZone:zone] init];
    copy.someproperty = [[self.someproperty copy] autorelease];
    return copy;
}

The difference is, that the first one just uses the name if its own class humanly readable just as if it was any other class. And the second one asks self for what class that is. Does that make a difference, or are both totally okay to use in this case?

+7  A: 

If you subclass MyClass, then the second example of -copyWithZone: returns an instance of the subclass. The first example doesn't, it returns an instance of MyClass.

Graham Lee
So inside a class when wanting to create an instance of that same class, one should always call [[self class] alloc] instead of [TheClass alloc]?
HelloMoon
It depends on whether a subclass should be dealing with that method. In -copyWithZone: a subclass could call your method via super, do extra configuration then return the result. Using [self class] is therefore preferable.
Graham Lee