NSMutableArray随机索引处的insertObject

时间:2012-10-02 03:43:20

标签: iphone objective-c ios nsmutablearray nsdictionary

我有一个包含对象和键的NSDictionary。钥匙包含姓名和号码。我想通过使用insertObject:atIndex:将这些对象插入到NSMutableArray中。对象是名称,数字是我想放置对象的索引。我现在知道NSMutableArrays能够在index:6处插入对象,如果没有1-5,那么我该如何实现呢?任何建议都非常感谢!

示例字典[dict objectForKey:@“array”]:

 preferences as whole (
        {
        Name = PowerDown;
        btnIndex = 3;
    },
        {
        Name = ClearCache;
        btnIndex = 5;
    },
        {
        Name = KillBGApps;
        btnIndex = 6;
    },
        {
        Name = InfoPanel;
        btnIndex = 2;
    },
        {
        Name = Lock;
        btnIndex = 4;
    },
        {
        Name = Reboot;
        btnIndex = 0;
    },
        {
        Name = Respring;
        btnIndex = 1;
    }
)

到目前为止我所拥有的内容,但是当在数组边界外添加对象时会崩溃

-(void)loadArray{

 self.buttons = [NSMutableArray array];


    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    tempArray = [buttonsPrefs objectForKey:@"buttonsToOrder"];


    for(NSDictionary * dict in tempArray)
    {
        if (dict) {

            NSString *btnName = [dict objectForKey:@"Name"];

            NSString *btnIndex = [dict objectForKey:@"btnIndex"];
            NSUInteger index = [btnIndex integerValue];

            NSLog(@"Name = %@",btnName);
            NSLog(@"at index %i",index);

            [self.buttons insertObject: btnName atIndex: index];
        }


    }

}

编辑:当用户移动单元格时,这些值的“索引”值会发生变化

- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath 
*)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
NSUInteger fromIndex = [fromIndexPath row];
NSUInteger toIndex = [toIndexPath row];
if (fromIndex == toIndex)
    return;
NSMutableDictionary *selectedButton = [[[_buttons objectAtIndex:fromIndex] retain] 
autorelease];
[_buttons removeObjectAtIndex:fromIndex];
[_buttons insertObject:selectedButton atIndex:toIndex];


//[buttonsPrefs setObject:_buttons forKey:@"buttonsToOrder"];
//[buttonsPrefs writeToFile:[self getFilePath] atomically: YES];


}

2 个答案:

答案 0 :(得分:2)

尝试根据yourDict计数用一些虚拟数据填充目标数组,如下所示:

for (int i=0, i<[yourDict count], ++i){
    [yourArray addObject:@"dummyData"];
}

当你需要insertObject时:

for(NSDictionary * dict in tempArray)
{
    if (dict) {

        NSString *btnName = [dict objectForKey:@"Name"];

        NSString *btnIndex = [dict objectForKey:@"btnIndex"];
        NSUInteger index = [btnIndex integerValue];

        [yourArray insertObject:btnName atIndex:index];
        [yourArray removeObjectAtIndex:index+1];
    }
}

答案 1 :(得分:0)

NSMutableArray insertObject: atIndex:

根据苹果文档`

  

“请注意,NSArray对象与C数组不同。即使如此   在创建数组时指定大小,指定的大小为   被视为“暗示”;数组的实际大小仍为0.这个   意味着您不能在大于的索引处插入对象   数组的当前计数。“

只能填写有效的数组值集。您可以做的两件事。

  1. 排序并填充数组
  2. 使用字符串填充一些默认对象(不能为nil),然后替换它。如果要填充数组中的所有值,此选项有效,因为以后使用时必须检查天气值是否正确或者默认值在该位置