我在一些遗留过多重复的旧代码中忙得不可开交。我正在尝试将其削减。
addCustomDataToJsonMap
我很乐意在函数顶部存储任何视图控制器的通用版本,并在其中填充适当的视图控制器,然后一次调用self.activeUUID setter。像这样:
- (IBAction)unwindWithNewData:(UIStoryboardSegue *)segue {
if ([segue.sourceViewController isKindOfClass:DistantVC1.class]) {
DistantVC1 *sourceVC = (DistantVC1 *)segue.sourceViewController;
self.activeUUID = sourceVC.data.uuid;
} else if ([segue.sourceViewController isKindOfClass:DistantVC2.class]) {
DistantVC2 *sourceVC = (DistantVC2 *)segue.sourceViewController;
self.activeUUID = sourceVC.data.uuid;
} else if ([segue.sourceViewController isKindOfClass:DistantVC3.class]) {
DistantVC3 *sourceVC = (DistantVC3 *)segue.sourceViewController;
self.activeUUID = sourceVC.data.uuid;
} else if ([segue.sourceViewController isKindOfClass:DistantVC4.class]) {
DistantVC4 *sourceVC = (DistantVC4 *)segue.sourceViewController;
self.activeUUID = sourceVC.data.uuid;
}
}
有什么想法吗?谢谢!
答案 0 :(得分:2)
是的,根据评论使用协议。
@protocol ActiveIdProvider
@property NSString *activeUUID
@end
@interface DistantVC1 : UIViewController <ActiveIdProvider> //repeat this block for each DistantVC class you have
@property NSString *activeUUID
@end
- (IBAction)unwindWithNewData:(UIStoryboardSegue *)segue {
ActiveIdProvider *sourceVC;
if ([segue.sourceViewController isKindOfClass:DistantVC1.class]) {
sourceVC = (DistantVC1 *)segue.sourceViewController;
} else if ([segue.sourceViewController isKindOfClass:DistantVC2.class]) {
sourceVC = (DistantVC2 *)segue.sourceViewController;
} else if ([segue.sourceViewController isKindOfClass:DistantVC3.class]) {
sourceVC = (DistantVC3 *)segue.sourceViewController;
} else if ([segue.sourceViewController isKindOfClass:DistantVC4.class]) {
sourceVC = (DistantVC4 *)segue.sourceViewController;
}
self.activeUUID = sourceVC.data.uuid;
}
答案 1 :(得分:0)
这是Swift 4.2版本:
protocol ActiveIDProvider {
var activeUUID: String { get }
}
class myVC1: UIViewController { }
extension myVC1: ActiveIDProvider {
var activeUUID: String {
get {
return "1"
}
}
}
@IBAction func unwindWithNewData(_ segue: UIStoryboardSegue) {
var sourceVC: ActiveIDProvider
if segue.source.isKind(of: myVC1.self) {
sourceVC = segue.source as! myVC1
} else if segue.source.isKind(of: myVC2.self) {
sourceVC = segue.source as! myVC2
} else if segue.source.isKind(of: myVC3.self) {
sourceVC = segue.source as! myVC3
} else if segue.source.isKind(of: myVC4.self) {
sourceVC = segue.source as! myVC4
}
self.activeUUID = sourceVC.activeUUID
}