使用NSMutableDictionary将对象保存到数组

时间:2011-10-06 20:37:03

标签: ios4 nsmutablearray plist nsmutabledictionary

我一直在尝试将一个对象作为NSMutableDictionary添加到我的数组中,我从另一个视图访问它,它似乎不起作用。我希望能够将数据存储在我从NSDictionary访问的plist中。

-(void)saveAlarm:(id)sender {

    // Adding object for alarm to AlarmViewController

    alarmArrayCopy = alarmViewController.alarmsTime;

    NSMutableDictionary *newAlarm =  [[NSMutableDictionary alloc] init];
    [newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
    [newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
    [alarmArrayCopy addObject:(newAlarm)];

    // Dismissing and tiding up.

    [self.navigationController dismissModalViewControllerAnimated:YES];
    [newAlarm release];
}

更新:如何将NSDictionary添加到我的plist数据库(我的数组是一个数组)?

这是一些新代码,我将NSMutableDictionary更新为NSDictionary,因为在我的plist中你只能使用普通词典而不是可变词典。但现在它崩溃并给了我一个Thread 1:Program received signal: "SIGABRT".

NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"data.plist"];

// Adding object for alarm to AlarmViewController

NSDictionary *newAlarm =  [[NSDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:[NSString stringWithFormat:@"%@", alarmPicker.date] forKey:TIME_KEY];
[newAlarm writeToFile:finalPath atomically:NO];

- (IBAction)saveAlarm:(id)sender {

// Adding object for alarm to AlarmViewController

NSString *time = [NSString stringWithFormat:@"%@", alarmPicker.date];
NSString *label = [NSString stringWithFormat:@"%@",labelTextField.text];

NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:label, LABEL_KEY,time, TIME_KEY, nil];
self.alarmArrayCopy = alarmViewController.alarmsTime;
[alarmArrayCopy addObject:(newAlarm)];

// Dismissing and tiding up.
[newAlarm release];
[self.navigationController dismissModalViewControllerAnimated:YES];

}

2 个答案:

答案 0 :(得分:2)

首先,您应该使用setObject:forKey:方法将对象添加到NSMutableDictionary。其次,如果您使用initWithObjectsAndKeys:,则应使用NSDictionary方法。

setValue:forKey键值编码协议的一种方法。那是在这里描述的“ Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?

所以,你应该这样做,

NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:
                                               labelTextField.text, LABEL_KEY,
                                               alarmPicker.date, TIME_KEY, nil];

答案 1 :(得分:1)

[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];

我不太确定,但我猜你的错误是因为你无法将一个NSDate对象的实例发送到setValue:forKey方法。您可以使用setObject:forKey或通过[NSString stringWithFormat:"%@", alarmPicker.date]将NSDate更改为NSString。

希望有所帮助。