2012-07-20 62 views
1

关键我已经做了如下变化值在字典

NSDictionary *dic=[[NSDictionary alloc] initWithObjectsAndKeys:a1,@"0",a2,@"1",a3,@"2",a4,@"3", nil]; 
    NSDictionary *userbtn=[[NSDictionary alloc] initWithObjectsAndKeys:dic,@"button", nil]; 
    [[NSUserDefaults standardUserDefaults] registerDefaults:userbtn]; 

我想改变的关键,当我在tableview中移动单元格。 我发现钥匙的价值不能改变。

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 
{ 
    NSUInteger fromRow = [sourceIndexPath row]; 
    NSUInteger toRow = [destinationIndexPath row]; 

} 

我该怎么办......在上述方法中。

回答

0

密钥对于任何字典都应该是唯一且不变的。请将您的dic作为钥匙button的值。您可以使用setValue:forKey更改该值。

0

正如维涅什说重点应该是唯一的,因此不能改变,但它的内容是可以改变的:

NSMutableDictionary *dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:a1,@"0",a2,@"1",a3,@"2",a4,@"3", nil]; 
NSMutableDictionary *userbtn=[[NSDictionary alloc] initWithObjectsAndKeys:dic,@"button", nil]; 
[[NSUserDefaults standardUserDefaults] registerDefaults:userbtn]; 

现在

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath 
{ 
    NSUInteger fromRow = [sourceIndexPath row]; 
    NSString *fromstr = [[userbtn objectForKey:@"button"]objectForKey:[NSString stringWithFormat:@"%d",fromRow]]; // firstly take content at index before interchanging 

    NSUInteger toRow = [destinationIndexPath row]; 
    NSString *tostr = [[userbtn objectForKey:@"button"]objectForKey:[NSString stringWithFormat:@"%d",toRow]]; // firstly take content at index before interchanging 

[[userbtn objectForKey:@"button"] setObject:fromstr forKey:[NSString stringWithFormat:@"%d",toRow]]; //interchange value but key is same 

[[userbtn objectForKey:@"button"] setObject:tostr forKey:[NSString stringWithFormat:@"%d",fromRow]];//interchange value but key is same 

} 
+0

恩......非常感谢。我犯了一个错误,我忘了NSMutableDictionary。我在NSDictionary中存储数据...所以...许多方法是有限的。 – user1535023 2012-07-20 05:49:17

+0

您只需将fromRow与toRow交换即可。那么从哪里来的数据呢?它让我陷入困境。字典不像数组那样灵活......仅仅因为它的数据拥有一把钥匙....... – user1535023 2012-07-20 07:11:39

+0

e ....我修好了它。没有别的难题 – user1535023 2012-07-20 07:43:04

0
NSDictionary *mydic=[[NSDictionary alloc] initWithObjectsAndKeys:@"Object Zero",@"0",@"Object One",@"1",@"Object Two",@"2",@"Object Three",@"3", nil]; 
      [[NSUserDefaults standardUserDefaults] setObject:mydic forKey:@"MyDictionary"]; 
      [[NSUserDefaults standardUserDefaults] synchronize]; 

       // then for replacing values 
      [[[[NSUserDefaults standardUserDefaults] objectForKey:@"MyDictionary"] mutableCopy] setObject:@"Object DOUBLE Zero" forKey:@"0"]; 
       // above code will replace string object @"Object Zero" to @"Object DOUBLE Zero" for key @"0" 
      [[NSUserDefaults standardUserDefaults] synchronize];