How to do that without having to \"scroll\" the entire given array with a \"for\" loop?
The best I can come up with is:
NSMutableArray *replacementArray = [NSMutableArray array];
[originalArray enumerateObjectsUsingBlock:
^(id obj, NSUInteger index, BOOL *stop)
{
[replacementArray addObject:[[obj mutableCopy] autorelease]];
}
];
Which more or less just tells the originalArray
to construct the for loop for you. And if anything it's more work than:
NSMutableArray *replacementArray = [NSMutableArray array];
for(id obj in originalArray)
[replacementArray addObject:[[obj mutableCopy] autorelease]];
I wrote a dictionary method on NSArray to be able to write cleaner functional code
-(NSArray *)arrayByPerformingBlock:(id (^)(id))performBlock
{
NSMutableArray *array = [NSMutableArray array];
for (id element in self)
[array addObject:performBlock(element)];
return [NSArray arrayWithArray:array];
}
usage:
arrayWithStrings = [arrayWithStrings arrayByPerformingBlock:^id(id element) {return [[element mutableCopy] autorelease];}];
This was inspired by list comprehensions I know from Python. I also wrote versions of this methods with testing. See my arraytools.
Since nobody seems to agree with my comment that this is a duplicate of Better way to convert NSArray of NSNumbers to array of NSStrings, here's the same answer again:
NSArray * arrayOfMutableStrings = [arrayOfStrings valueForKey:@"mutableCopy"];
From the docs:
valueForKey:
Returns an array containing the results of invokingvalueForKey:
usingkey
on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key
The key to retrieve.Return Value
The value of the retrieved key.Discussion
The returned array containsNSNull
elements for each object that returnsnil
.