开发者

Objective-C subclasses question

开发者 https://www.devze.com 2022-12-26 14:51 出处:网络
I have a c开发者_C百科lass called Level, which is a subclass of NSObject. Then I have a class called Level_1_1 which is a subclass of Level.

I have a c开发者_C百科lass 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. 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.).

0

精彩评论

暂无评论...
验证码 换一张
取 消