Objective-C中的DRY元代码

Dan*_*ark 1 dry objective-c

我在Objective-C中遇到过这种情况:

[aCoder encodeObject:self.control forKey:@"control"];
[aCoder encodeObject:self.command forKey:@"command"];
[aCoder encodeObject:self.channel forKey:@"channel"];
[aCoder encodeObject:self.data1 forKey:@"data1"];
Run Code Online (Sandbox Code Playgroud)

在Ruby或Groovy中,我可以用块来做这个,并且只需要一点点就可以有一行而不是四行.我知道Objective-C有很多动态特性.如何提取这些代码?

Ale*_*yne 5

您可以使用 performSelector:withObject:

for (NSString *key in arrayOfKeys) {
  SEL aSelector = NSSelectorFromString(key);
  id anObject = [self performSelector:aSelector withObject:nil];
  [aCoder encodeObject:anObject forKey:key];
}
Run Code Online (Sandbox Code Playgroud)

这是在运行时动态调用方法的方法,只使用该方法的名称作为字符串.该withObject:参数是作为方法的单个参数传递的单个对象,如果它采用一个.

如果它需要多个参数,或者采用非对象参数,则必须查看更复杂的问题NSInvocation和它的伙伴NSMethodSignature.可悲的是,它们不是很简单,但它们确实可以让你获得一些令人印象深刻的动力,即使它们的使用是复杂和丑陋的.