如何在iOS中避免使用NSString过多的if-else语句?

ylo*_*esy 2 if-statement objective-c nsstring ios

大家好,我想使用iOS8的新APN来处理通知操作.在这个方法中:

- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
     forRemoteNotification:(NSDictionary *)notification
         completionHandler:(void (^)())completionHandler {

      if ([identifier isEqualToString:@"ACCEPT_IDENTIFIER"]) {
          [self handleAcceptActionWithNotification:notification];
      }
      else if([identifier isEqualToString:@"MAYBE_IDENTIFIER"]) {
          [self handleMaybeActionWithNotification:notification];
      }
      else if ([identifier isEqualToString:@"REJECT_IDENTIFIER"]) {
          [self handleRejectActionWithNotification:notification];
      }
      else if....blah blah blah..
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我可能不得不在将来用NSString编写太多if-else语句,并且我知道某种方法可以避免使用过多的if-else语句,例如使用switch,但它不适用于字符串或NSString情况.

是避免在此字符串或NSString情况下编写过多if-else语句的解决方案吗?提前致谢.

tia*_*tia 5

您可以将所有选择器放在字典映射中

NSDictionary* handleMap = @{ 
    @"ACCEPT_IDENTIFIER" : NSStringFromSelector(@selector(handleAcceptActionWithNotification:))
    @"MAYBE_IDENTIFIER" : NSStringFromSelector(@selector(handleMaybeActionWithNotification:))
    @"REJECT_IDENTIFIER" : NSStringFromSelector(@selector(handleRejectActionWithNotification:)])
};

NSString* selString = handleMap[identifier];
if (selString) {
    SEL sel = NSSelectorFromString(selString);
    [self performSelector:sel withObject:notification];
}
Run Code Online (Sandbox Code Playgroud)

handleMap 应该声明为成员变量,因此它只会被初始化一次.