views:

153

answers:

1

I have a class called Level, which is a subclass of NSObject.

Then I have a class called Level_1_1 which is a subclass of Level.

Is it allowed to type like

Level* aLevel = [Level_1_1 alloc];

instead of

Level_1_1* theLevel = [Level_1_1 alloc];

? :)

I try it and I don't get any warnings, just wondering if it's okay to do?

+5  A: 

This is allowed; but there are two things you should keep in mind:

  1. Never, ever call +alloc without chaining it with -init or an -initWith*, unless you are mucking about with the runtime.
  2. You might want to reconsider your design if you are calling classes things like Level_1_1. You might, for example, want to have a generic Level class and some manner of level description data tied to it, so you don't have to hard-code every level; making stuff pretty much impossible to extend without massive effort on your part.

Back to the point:

SomeClass *aSomeclass = [[MySomeClass alloc] init];

is perfectly acceptable (assuming MySomeClass inherits from SomeClass). In fact, this happens a lot without you even noticing: You never, for example, actually get an NSString, even when calling [[NSString alloc] init], as in:

// This is an NSConstString masquerading as an NSString
NSString *aString = @"This is an NSConstString";
// This probably gives you an NSConcreteString, or something of the kind
NSString *anotherString = [NSString stringWithString:aString];

You could even add a completely wrong type to your class. E.g.

NSArray *someString = @"Not An Array!";
NSLog(@"%s", [someString UTF8String]);  // this works, but creates
                                        // a compile-time warning
NSLog(@"%u", [someString count]);       // this creates a runtime error,
                                        // but none while compiling

This string instances is still perfectly usable, but the compiler can't warn you about obvious errors anymore, because it thinks it's an NSArray. Also, Objective-C 2.0 properties won't work properly (but the compiler is gonna warn you about it.).

Williham Totland
Thanks a lot. ;) I don't use alloc, I use new, which I assume is alloc and init in one. Thanks anyway :)
Johannes Jensen
Then please use `#new` it in your examples and please don't assume what `#new` does but look it up in the documentation.
nils