天天看點

iOS動态運作時方法

在某些時候,程式可能需要根據擷取的參數來決定調用的方法。

要實作這樣的功能,就需要使用到動态運作時方法了。

首先需要定義好接口,以便調用。

然後就是動态調用定義好的方法。

這裡有兩種方法,

第一種:

// 有參數則需要加上冒号
SEL sel = NSSelectorFromString(@"save:");

MyObject obj = [MyObject new];

[obj performSelector:sel withObject:@{@"1":@"one"}];      

使用第一種方法,程式會出現警告。

第二種:(使用方法指針調用)

MyObject obj = [MyObject new];

SEL sel = NSSelectorFromString(@"save:");

IMP imp = [obj methodForSelector:sel];

/*
 * id 對象
 * SEL 對象的方法
 * id 方法的參數
 */    
void (*func)(id, SEL, id) = (void *)imp;

// 或者可以這樣寫

// ((void (*)(id, SEL, id))[obj methodForSlector:sel])(obj, sel, @{@"1":@"one"});

func(manager, sel, @{@"1":@"one"});      

另外,id類型的熟練使用非常重要。

NSString *param = @"{\"mm\":\"iosqiao\",\"yhm\":\"123456\"}";
  id obj = [NSJSONSerialization
      JSONObjectWithData:[param dataUsingEncoding:NSUTF8StringEncoding]
                 options:0
                   error:nil];
  MyObject *manager = [MyObject new];
  if (!manager) {
    return;
  }
  SEL sel = NSSelectorFromString(@"saveStorage:");
  IMP imp = [manager methodForSelector:sel];
  void (*func)(id, SEL, id) = (void *)imp;
  func(manager, sel, obj);      

轉載于:https://www.cnblogs.com/hd1992/p/5648800.html