简体   繁体   English

Objective-C子类问题

[英]Objective-C subclasses question

I have a class called Level, which is a subclass of NSObject. 我有一个名为Level的类,它是NSObject的子类。

Then I have a class called Level_1_1 which is a subclass of Level. 然后我有一个名为Level_1_1的类,它是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. 永远不要在没有用-init-initWith*链接的情况下调用+alloc ,除非你正在捣乱运行时。
  2. You might want to reconsider your design if you are calling classes things like Level_1_1 . 如果您要调用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; 例如,您可能希望拥有一个通用的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 ). 是完全可以接受的(假设MySomeClass继承自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: 事实上,如果没有你注意到这种情况会发生很多事情:例如,即使调用[[NSString alloc] init] ,你也永远不会获得NSString ,如:

// 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. 这个字符串实例仍然完全可用, 但编译器不能再警告你有关明显的错误,因为它认为它是一个NSArray。 Also, Objective-C 2.0 properties won't work properly (but the compiler is gonna warn you about it.). 此外,Objective-C 2.0属性将无法正常工作(但编译器会向您发出警告。)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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