How to do sparse array in Cocoa

前端 未结 4 921
不知归路
不知归路 2020-12-09 21:38

I have an undetermined size for a dataset based on unique integer keys.

I would like to use an NSMutableArray for fast lookup since all my keys are inte

4条回答
  •  感情败类
    2020-12-09 22:21

    It sounds like your needs would be better met with an NSMutableDictionary. You will need to wrap the ints into NSNumber objects as follows:

    -(void)addItem:(int)key value:(id)obj
    {
        [data setObject:obj forKey:[NSNumber numberWithInt:key]];
    }
    
    -(id)getItem:(int)key
    {
        return [data objectForKey:[NSNumber numberWithInt:key]];
    }
    

    There's no easy was to enlarge the size of an NSMutableArray, since you cannot have nil objects in the in-between slots. You can, however, use [NSNull null] as a 'filler' to create the appearance of a sparse array.

提交回复
热议问题