简体   繁体   中英

Objective-C subclasses question

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?

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. Eg

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.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM