2012-07-20 64 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];