如何在Cocoa中做稀疏数组 [英] How to do sparse array in Cocoa

查看:124
本文介绍了如何在Cocoa中做稀疏数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于唯一整数键的数据集的大小。



我想使用 NSMutableArray 快速查找,因为所有的键都是基于整数的。



我想这样做。

  NSMutableArray * data = NSMutableArray array]; //只是创建0尺寸

然后后来人们会开始用整数索引唯一),所以我只是想做这样的事情...

  if([data count]< index)
[data resize:index]; //?你如何调整大小

并调整数组大小以便我可以...

  [data insertObject:obj atIndex:index]; 

所有最后尺寸和新尺寸之间的插槽为零,最终将在以后填充。 / p>

所以我的问题是如何调整现有的 NSMutableArray



谢谢,
罗马

解决方案

听起来你的需求会更好地满足 NSMutableDictionary 。您将需要将 int 包装到 NSNumber 对象中,如下所示:

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

- (id)getItem:(int)key
{
return [data objectForKey:[NSNumber numberWithInt:key]
}

不容易放大 NSMutableArray ,因为您不能在中间插槽之间有nil个对象。但是,您可以使用 [NSNull null] 作为'填充'来创建稀疏数组的外观。


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 integer based.

I want to do this.

NSMutableArray* data = [NSMutableArray array]; // just create with 0 size

then later people will start throwing data at me with integer indexes (all unique) so I just want to do something like this...

if ([data count] < index)
    [data resize:index];  // ? how do you resize

and have the array resized so that i can then do...

[data insertObject:obj atIndex:index];

with all the slots between last size and new size being zero which will eventually be filled in later.

So my question is how do I resize an existing NSMutableArray?

Thanks, Roman

解决方案

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.

这篇关于如何在Cocoa中做稀疏数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆