我有一个包含对象和键的 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];
}