且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

objc写一个NSMutableArray不连续索引替换对象的方法

更新时间:2022-08-21 14:22:55

NSMutableArray内置的方法-(void)replaceObjectsAtIndexes:(NSIndexSet*)set withObjects:(NSArray*)objs
只能替换一段连续索引内的对象,比如2 to 10之间的对象,如果我想要替换1,3,5索引位置的对象需要自己写代码。
在ruby中对于数组对象有一个values_at方法可以取得不连续索引的对象:

2.2.1 :048 > ary = %w[a b c d e f g]
 => ["a", "b", "c", "d", "e", "f", "g"] 
2.2.1 :049 > ary.values_at(*[1,3,5])
 => ["b", "d", "f"] 

如果是替换不连续索引的对象,稍微麻烦点:

2.2.1 :053 > idxes
 => [1, 3, 5] 
2.2.1 :054 > objs
 => ["X", "X", "X"] 
2.2.1 :055 > idxes.zip(objs)
 => [[1, "X"], [3, "X"], [5, "X"]] 
2.2.1 :056 > idxes.zip(objs).each {|i,v|ary[i] = v}
 => [[1, "X"], [3, "X"], [5, "X"]] 
2.2.1 :057 > ary
 => ["a", "X", "c", "X", "e", "X", "g"] 

如果idxes数量小于objs则忽略多余的对象,反之如果idxes数量大于objs则用nil补足:

2.2.1 :062 > objs = %w[X X X]
 => ["X", "X", "X"] 
2.2.1 :063 > idxes = [1,6]
 => [1, 6] 
2.2.1 :064 > idxes.zip(objs).each {|i,v|ary[i] = v}
 => [[1, "X"], [6, "X"]] 
2.2.1 :065 > ary
 => ["a", "X", "c", nil, "e", nil, "X"] 


2.2.1 :059 > objs = []
 => [] 
2.2.1 :060 > idxes.zip(objs).each {|i,v|ary[i] = v}
 => [[1, nil], [3, nil], [5, nil]] 
2.2.1 :061 > ary
 => ["a", nil, "c", nil, "e", nil, "g"] 

下面写一个objc中类似的实现:

#import <Foundation/Foundation.h>

@interface NSMutableArray (HyRandReplace)
@end

@implementation NSMutableArray (HyRandReplace)
-(void)replaceObjectsAtIndexesRand:(NSArray*)idxes withObjects:(NSArray*)objs{
    NSUInteger count_idxes = [idxes count];
    //NSUInteger count_objs = [objs count];
    for(NSUInteger i = 0;i < count_idxes;i++){
        NSUInteger x = [idxes[i] intValue];
        @try{
            [self replaceObjectAtIndex:x withObject:objs[i]];
        }
        @catch(NSException *e){
            NSLog(@"%@:%@",e.name,e.reason);
            [self replaceObjectAtIndex:x withObject:[NSNull null]];
        }
    }
}
@end

int main(void){
    @autoreleasepool{
        NSArray *idxes = @[@1,@3,@5];
        //NSArray *objs = @[@"LOVE",@"FOR"];
        NSArray *objs =@[];
        NSMutableArray *mary = [@[@"a",@"and",@"b",@"for",@"ever",@"..."] 
            mutableCopy];
        NSLog(@"%@",mary);
        [mary replaceObjectsAtIndexesRand:idxes withObjects:objs];
        NSLog(@"%@",mary);
    }
    return 0;
}

当然ruby里也可以做类似的操作,why not?ruby比objc还要动态:

2.2.1 :066 > class Array
2.2.1 :067?>   def replace_rand(idxes,objs)
2.2.1 :068?>     idxes.zip(objs).each {|i,v|self[i] = v}
2.2.1 :069?>     end
2.2.1 :070?>   end
 => :replace_rand 
2.2.1 :073 > ary
 => ["a", "b", "c", "d", "e", "f", "g"] 
ary.replace_rand          
2.2.1 :074 > ary.replace_rand(idxes,objs)
 => [[1, "X"], [6, "X"]] 
2.2.1 :075 > ary
 => ["a", "X", "c", "d", "e", "f", "X"] 

see!ruby扩展类要比objc简单的多,所以看swift的了 :)