开发者

iOS -- mapping a method to an array

Is there a more concise way to do the following in iOS?

Suppose we have:

NSArray *existingArray;

and also our object self has a method someMethod which can take the objects in existingArray as input and returns objects of class Foo. We could create a new array *derivedArray by applying someMethod to the objects in existingArray as 开发者_如何学编程follows:

NSMutableArray *derivedArray = [[NSMutableArray alloc]init];
for (id obj in existingArray) {
  [derivedArray addObject: [self someMethod: obj]];
}

My question is, is there a more concise way to do that? Something like:

NSArray *derivedArray = [existingArray arrayByMappingMethod: someMethod withObject: self];  


No. There is a makeObjectsPerformSelector: method (and a few other related ones), but none allow you to get a result from the calls. You could, of course, add your method as a category on NSArray, but Apple has not provided a method to do this.

In terms of performance improvements, change

[[NSMutableArray alloc] init];

to

[[NSMutableArray alloc] initWithCapacity:[existingArray count]];

This will allow the array to allocate memory for all of the objects at once, instead of reallocating every time you add an object.


Inspire48's comment's probably the best idea. If you're targeting iOS 4+, Mike Ash wrote a number of collection utilities that are available on GitHub. It includes a map method.

It requires iOS 4 because it leverage blocks.


Have a look at -[NSArray filteredArrayUsingPredicate:].

Edit: I may have assumed too much about what your -someMethod: method does. I guessed that it tests obj and returns either obj or nil, but just realized that it could easily return something completely different. Another possible answer, then, is -[NSArray makeObjectsPerformSelector:], but that would require that obj's class contain -someMethod rather than the object doing this filtering.

Edit 2: One more possibility is -valueForKey:, which when applied to an array will return an array of the results from sending -valueForKey: to the objects in the array. Again, though, the objects have to respond to -valueForKey: for the given key.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜