【发布时间】:2012-10-02 03:43:19
【问题描述】:
我有一个包含对象和键的 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];
}
【问题讨论】:
-
也许您应该按照
btnIndex的升序对您的偏好进行排序,然后将值附加到您的数组中? -
这适用于给定的示例,但该数组可以是任何顺序,例如 3、6、2、1、0、4、5。一旦用户上下移动单元格,它将更改该名称的整数值
-
是的,Kevin 是对的,只需根据 btnIndex 对数组进行排序。这样做有什么具体原因吗?
-
从某种意义上说,如果它总是相同的话,你们俩都是对的,但是如果你看看我编辑过的问题,我认为它会更清楚,它比只是升序更复杂。我非常感谢您的帮助
-
初始化数组时,用 [NSNull null] 对象填充它并根据需要替换它们。
标签: iphone objective-c ios nsmutablearray nsdictionary