假设我有一个特定的对象类,它定义了一个返回有关该类的简单信息的类方法,因此:
+ (NSInteger) defaultValueForClass {
return 5;
}
现在,假设我有一系列子类,每个子类都覆盖此方法以提供不同的信息。我的问题是:如何在不知道正在执行哪个具体子类的情况下调用该类方法,从而使用相关的子类方法?我不能简单地去:
[[anObject class] defaultValueForClass]
...因为编译器此时不知道我的自定义子类方法。
对不起我之前的帖子,我错了,只需定义一个协议然后检查你的类是否符合ToProtocol,或者检查给定的类是否“isSubclassOfClass”
为我工作。
// car.m
#import <Foundation/Foundation.h>
@interface Car : NSObject
+ (void)make;
@end
@interface Honda : Car
@end
@interface Porsche : Car
@end
@implementation Car
+ (void)make { NSLog(@"generic"); }
@end
@implementation Honda
+ (void)make { NSLog(@"Honda"); }
@end
@implementation Porsche
+ (void)make { NSLog(@"Porsche"); }
@end
int main() {
Porsche *porsche = [[Porsche alloc] init];
[[porsche class] make];
Car *supercar = (Car *)[[Honda alloc] init];
[[supercar class] make];
return 0;
}
并且编译和执行输出没有显示错误或警告。
$ clang -framework 基础 car.m -o car.o $ ./car.o 2012-07-01 01:53:46.559 car.o[8127:707] 保时捷 2012-07-01 01:53:46.561 car.o[8127:707] 本田
你使用的是什么版本的 Xcode 和 GCC?是旧的 GCC 还是 LLVM-GCC?