convert NSArray of NSString(s) to NSArray of NSMutableString(s)

和自甴很熟 提交于 2019-12-04 06:10:00

问题


How to do that without having to "scroll" the entire given array with a "for" loop?


回答1:


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 invoking valueForKey: using key 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 contains NSNull elements for each object that returns nil.




回答2:


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]];



回答3:


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.



来源:https://stackoverflow.com/questions/8170809/convert-nsarray-of-nsstrings-to-nsarray-of-nsmutablestrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!