2

我得到的错误

-[NSDictionary initWithObjects:forKeys:]:对象数 (0) 与键数 (2) 不同'

这是我保存 plist 的代码。

    @interface setting : UIViewController{
    UIDatePicker *datePicker;
    IBOutlet UILabel * morningtime;
    UIDatePicker *afternoonpicker;
    NSString*morningtime1;
    NSString*afternoontime1;
     IBOutlet UILabel *afternoontime;
}
@property (nonatomic,retain) IBOutlet UIDatePicker *datePicker;
@property (strong, nonatomic) IBOutlet UIDatePicker *afternoonpicker;

@property (nonatomic, retain) IBOutlet NSString *morningtime1;

@property (nonatomic, retain) IBOutlet NSString *afternoontime1;
@property (nonatomic, retain) IBOutlet UILabel *morningtime;

@property (nonatomic, retain) IBOutlet UILabel *afternoontime;
@property (weak, nonatomic) IBOutlet UIButton *morning;




- (IBAction)savetext:(id)sender {
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

    self.morningtime1 = morningtime.text;
    self.afternoontime1 = afternoontime.text;
    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: morningtime1, afternoontime1, nil] forKeys:[NSArray arrayWithObjects: @"Morning", @"Afternoon", nil]];

    NSString *error = nil;
    // create NSData from dictionary
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

    // check is plistData exists
    if(plistData)
    {
        // write plistData to our Data.plist file
        [plistData writeToFile:plistPath atomically:YES];
    }
    else
    {
        NSLog(@"Error in saveData: %@", error);
    }
}
4

2 回答 2

8

morningtime1几乎可以肯定nil在这里,过早地结束了数组列表。

如果您在此处使用了新的数组字面量语法:

@[morningtime1, afternoontime1];

您会崩溃,因为将 nil 分配给NSArray元素是非法的。

于 2013-04-09T18:32:03.403 回答
0

这一行:

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: morningtime1, afternoontime1, nil] forKeys:[NSArray arrayWithObjects: @"Morning", @"Afternoon", nil]];

应该:

NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: self.morningtime1, self.afternoontime1, nil] forKeys:[NSArray arrayWithObjects: @"Morning", @"Afternoon", nil]];

换句话说,引用属性,而不是 ivars。正如您所拥有的,morningtime1永远不会设置 ivar(您设置的属性实际上是设置生成的 ivar named _morningtime1)。

边注:

摆脱@synthesize属性的任何显式 ivars 和行。这将避免这种混乱。

于 2013-04-09T18:32:09.733 回答