【问题标题】:iOS Adding Method name to NSDictionary and calling it afterwardsiOS将方法名称添加到NSDictionary并随后调用它
【发布时间】:2014-05-28 06:17:33
【问题描述】:

我正在尝试这件事,但似乎无法正确处理.. 我有一个名为 dataDictionaryNSMutableDictionary2 KeyValue 对,IdMethodName

NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithCapacity:1];
[dataDictionary setValue:@"1.0" forKey:@"Id"];
[dataDictionary setValue:@"myMethod" forKey:@"MethodName"];

虽然我的方法是

-(void)myMethod{ … }

所以我需要做的是获取方法名称[dataDictionary valueForKey:@"MethodName"]; 并调用该方法......

任何帮助都会很棒..提前感谢

【问题讨论】:

    标签: ios objective-c nsdictionary


    【解决方案1】:

    您可以使用NSSelectorFromStringNSStringFromSelector 将其存储为NSString

    或喜欢NSValue

    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: 
                           [NSValue valueWithPointer:@selector(foo)], @"foo",
                           nil];
    
    SEL aSel = [[dict objectForKey:@"foo"] pointerValue];
    

    更多信息: Add method selector into a dictionary, Store selector as value in an NSDictionary

    【讨论】:

      【解决方案2】:
      NSString *myMethodInStringFormat=[dataDictionary valueForKey:@"MethodName"];
      
      SEL mySelector=NSSelectorFromString(myMethodInStringFormat);
      
      
      #pragma clang diagnostic push
      #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
      
      if (mySelector!=nil) {
      
              [self performSelector:mySelector];
      }
      
      
      #pragma clang diagnostic pop
      

      【讨论】:

      • nyc... 但它给出了内存泄漏错误PerformSelector may cause a leak because its selector is unknown
      • performSelector 行更改为[self performSelector:mySelector withObject:nil afterDelay:0.0]; 删除了警告
      【解决方案3】:

      在“Vijay-Apple-Dev.blogspot.com”的答案的帮助下,对其进行了一些修改以解决警告..

      NSString *myMethodInStringFormat = [dataDictionary valueForKey:@"MethodName"];
      
      SEL mySelector = NSSelectorFromString(myMethodInStringFormat);
      
      if (mySelector!=nil) {
      
              [self performSelector:mySelector withObject:nil afterDelay:0.0];
      }  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-28
        • 2019-11-19
        • 2017-12-16
        • 2015-08-25
        • 2011-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多