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

前端 未结 3 2061
长情又很酷
长情又很酷 2021-01-26 06:35

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

相关标签:
3条回答
  • 2021-01-26 06:45

    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]];
    
    0 讨论(0)
  • 2021-01-26 06:55

    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.

    0 讨论(0)
  • 2021-01-26 07:03

    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.

    0 讨论(0)
提交回复
热议问题