假设我有两个类,BulbDevice
和FanDevice
,两个都是Device
的子类,并且有一个像这样的方法签名:
+ (BOOL)isMyId:(NSInteger)someId;
如果我想创建一个类,我可以测试它:
if ([BulbDevice isMyId:someId]) {
Device *dev = [BulbDevice alloc] initWithId:someId];
}
但我真正想要的是在工厂类中创建一个工厂方法,在添加新设备时最小化:
+ (Device)createDevice:(NSInteger)someId {
// say I have an array registered
NSArray *arr = @[[BulbDevice class], [FanDevice class]];
// Loop through it.
Device *device;
for (Class *c in arr) {
// The idea is kind of like this but I'm not sure how to make it work
if ([c isMyId]) {
device = [[c alloc] init];
}
}
}
我的想法是我只需要在工厂方法中更新arr
。所以我觉得这样的事情很好。但我不知道如何使其发挥作用。
编辑:
我拿出了星号,但它不起作用:
for (Class c in arr) {
// Now I want to access the isMyId which is a static method,
// but I how do I cast to that class? I mean not an object of the class, but to that class itself.
if ([(Device)c isMyId:]) {
}
}
但我仍然需要一种方法来访问该类方法。错误说Used type 'Device' where arithmetic or pointer type is required
,即使它工作,我想访问类方法,而不是发送消息到对象。
或者我应该将NSString
存储在阵列中吗?但是很难找到访问类方法的方法。
Class
类型不是NSObject
类型,虽然it is a bit special它是对象或对象等效的,所以你能够发送消息并将其存储在你正在做的集合中。
您不使用星号,因为@MaxPevsner说,因为Class
不用作普通的指向对象的指针。可以把Class
想象成像id
这样的特殊类型,当你用它来引用一个物体时,它也没有得到*
。
如果我理解你想要实现的目标,那么你的方法似乎是正确的。
只有一件事需要修复:
for (Class c in arr)
c
变量不是指针 - 应删除星号。你的代码有效。