我正在开发我的第一个 iOS 应用程序,其中一部分使用一个协议,然后有许多遵循该协议的类。
@protocol unitLoadoutDataController <NSObject>
@required
- (void)setDefaultLoadout:(NSString *)unitType unitId:(NSNumber *)uniqueUnitId;
- (void)resizeDefaultLoadout:(NSString *)unitType unitId:(NSNumber *)uniqueUnitId number:(NSNumber *)models;
- (UIAlertController *)updateLoadout:(NSInteger)section row:(NSInteger)row unitType:(NSString *)unitType unitId:(NSNumber *)uniqueUnitId number:(NSNumber *)models;
@end
然后是一组使用它的类。例如
@interface heavyIntercessorSquad : NSObject <unitLoadoutDataController>
@end
@interface eradicatorSquad : NSObject <unitLoadoutDataController>
@end
这两者都包括我的协议定义的三种不同实现的方法。
当用户单击表格视图中列表中的一个单元时,我需要该类的一个实例,以便他们可以在下一个屏幕上配置它。在单击该行之前,我不知道我需要哪个类。
为了解决这个问题,我使用一组局部变量和一个大的 if/else 块来获取我需要的类。 selectedUnit.name 包含用户单击的小队的名称,并根据该值创建适当类型的类。一旦我有了指向我需要的类的指针,我就把它分配给squadToConfigure并调用我需要的方法。
这里是squadToConfigure 的定义,它保存创建后的类。
@property (weak, nonatomic) id <unitLoadoutDataController> squadToConfigure;
这是代码的子集,它根据 selectUnit.name 计算出我需要哪个类(到目前为止我有大约 30 个类)
heavyIntercessorSquad *heavyIntercessorSquadToConfigure;
eradicatorSquad *eradicatorSquadToConfigure;
if ([selectedUnit.name isEqualToString:@"Heavy Intercessor Squad"]) {
heavyIntercessorSquadToConfigure=[[heavyIntercessorSquad alloc] init];
self.squadToConfigure=heavyIntercessorSquadToConfigure;
}
else if ([selectedUnit.name isEqualToString:@"Eradicator Squad"]) {
eradicatorSquadToConfigure =[[eradicatorSquad alloc] init];
self.squadToConfigure= eradicatorSquadToConfigure;
}
[self.squadToConfigure setDefaultLoadout:self.selectedUnit.name
unitId:newUnitId];
有更优雅的方法吗?如何实例化由 selectedUnit.name 的值确定的类型的类并将其分配给 self.squadToConfigure 而无需大量 else 语句?
上面的代码目前运行良好,但一旦我有大量课程,就无法持续 - 目前我大约有 30 个课程。
您遇到的问题是您正在关闭文字字符串,这非常脆弱。至少,您需要手头有一个字典,它可以在您的
selectedUnit.name
可能性和您想要实例化的类之间进行映射。
如果名称可能性本身是常量而不仅仅是可能被错误键入的文字字符串,或者如果单元具有某种不可变且可靠的标识符,那么这将变得更加安全。但你还没有展示任何关于这些单位以及它们如何使用的信息,所以不可能说更多。
但是更复杂的方法可能是提前计划,使得
selectedUnit
本身有一个属性 is 与该单元对应的类,这样您就可以直接读取该属性并实例化。