Dan Rosenstark
Dan Rosenstark

Reputation: 69777

DRY meta-code in Objective-C

I have this type of situation in 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"];

In Ruby or Groovy I could do this with blocks and a tiny bit of messing around to have one line rather than four. I know Objective-C has many dynamic features. How can this code be distilled?

Upvotes: 1

Views: 167

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187184

You can use performSelector:withObject:

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

This is how you dynamically call a method at run time with only the name of that method as a string. The withObject: argument is a single object passed as as the single argument for a method, if it takes one.

If it takes more than one argument, or takes a non-object argument, you have to look into the far more complicated NSInvocation and it's buddy NSMethodSignature. Sadly, they are not very simple but they do allow you to achieve some impressive dynamism, if even their use is complicated and ugly.

Upvotes: 5

Related Questions