无法将对象保存到CoreData

时间:2015-09-18 20:08:19

标签: ios core-data

我的数据模型的实体为HYUser,属性为firstNamelastNameemailgenderphone 。当我检查我的.sqlite数据库时,没有任何内容。我已经附加了我应该保存对象的整个按钮操作。

- (IBAction)btnUserDataSave:(id)sender {
NSEntityDescription * entityDescription = [NSEntityDescription entityForName:@"HYUser" inManagedObjectContext:context];
NSManagedObject *newUser = [[NSManagedObject alloc]initWithEntity:entityDescription insertIntoManagedObjectContext:context];
NSString *gender = NULL;
NSError *error = nil;

[newUser setValue:self.txtfFirstName.text forKey:@"firstName"];
[newUser setValue:self.txtfLastName.text forKey:@"lastName"];
[newUser setValue:self.txtfPhoneNumber.text forKey:@"phone"];
[newUser setValue:self.txtfUserEmail.text forKey:@"email"];

if (self.segmentControlGender.selectedSegmentIndex == 0) {
    gender = @"Male";
}else if(self.segmentControlGender.selectedSegmentIndex == 1){
    gender = @"Female";
}else{
    NSLog(@"ERROR in gender saving");
}
[newUser setValue:gender forKey:@"gender"];

if ([self.txtfFirstName.text  isEqual: @""] || [self.txtfLastName.text  isEqual: @""] || [self.txtfPhoneNumber.text  isEqual: @""] || [self.txtfUserEmail.text  isEqual: @""]) {
    UIAlertController* errorPrompt = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Required Fields", @"Required Fields")
                                                                         message:NSLocalizedString(@"All fields are required to complete Sign-up. ", nil)
                                                                  preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK",nil)
                                                       style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

                                                       }];
    [errorPrompt addAction:okAction];
    [self presentViewController:errorPrompt animated:YES completion:NULL];

}else{
    if(![context save:&error]) {
        self.labelStatus.text = @"Error";
        NSLog(@"%@, %@", error, error.localizedDescription);
    }else{
        [context save:&error];
        self.labelStatus.text = @"Saved";

    }
}
}

4 个答案:

答案 0 :(得分:1)

我解决了这个问题,看起来它与我试图保存对象的方式有关。以下是我注册新用户的完整代码。

- (IBAction)btnUserDataSave:(id)sender {


HYUser* signUpUserObject = [NSEntityDescription insertNewObjectForEntityForName:@"HYUser" inManagedObjectContext:context];

NSString *gender = nil;
NSError *error = nil;

if ([self.txtfFirstName.text  isEqual: @""] || [self.txtfLastName.text  isEqual: @""] || [self.txtfPhoneNumber.text  isEqual: @""] || [self.txtfUserEmail.text  isEqual: @""]) {
    UIAlertController* errorPrompt = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Required Fields", @"Required Fields")
                                                                         message:NSLocalizedString(@"All fields are required to complete Sign-up. ", nil)
                                                                  preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK",nil)
                                                       style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

                                                       }];
    [errorPrompt addAction:okAction];
    [self presentViewController:errorPrompt animated:YES completion:NULL];

}
else {


    self.labelStatus.text = @"Saved";
    [signUpUserObject setValue:self.txtfFirstName.text forKey:@"firstName"];
    [signUpUserObject setValue:self.txtfLastName.text forKey:@"lastName"];
    [signUpUserObject setValue:self.txtfPhoneNumber.text forKey:@"phone"];
    [signUpUserObject setValue:self.txtfUserEmail.text forKey:@"email"];

    gender =  self.segmentControlGender.selectedSegmentIndex == 0 ? @"Male" : @"Female";

    [signUpUserObject setValue:gender forKey:@"gender"];

    if(![context save:&error]) {
        self.labelStatus.text = @"Error";
        NSLog(@"%@, %@", error, error.localizedDescription);
    }
    else {
        UIAlertController* errorPrompt = [UIAlertController alertControllerWithTitle:@"HairYourWay"
                                                                             message:NSLocalizedString(@"STR_NEW_USER_SIGN_UP_SUCCEEDED", @"Success")
                                                                      preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK",nil)
                                                           style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                                                               [self.navigationController popViewControllerAnimated:YES];
                                                           }];
        [errorPrompt addAction:okAction];
        [self presentViewController:errorPrompt animated:YES completion:NULL];

    }
}
}

答案 1 :(得分:0)

尝试从核心数据中取回对象,以确保它没有进入。

您可以尝试这样做,而不是initWithEntity。

[NSEntityDescription insertNewObjectForEntityForName:@"HYUser" inManagedObjectContext:context];

您要保存上下文两次,第二次是第一次成功。这不会导致问题,但不需要。

此外,如果用户未通过字段验证,则您已在上下文中创建了该对象。是否需要或者应该在创建托管对象之前进行验证?

答案 2 :(得分:0)

要检查的事项:

context为零,还是真的指向NSManagedObjectContext?它是如何创建的?它是否有持久的商店协调员?

是否有任何中间对象为零? entityForName:参数中的拼写错误将导致插入无提示失败。也许添加NSParamterAssert(newUser)。如果爆炸,你知道要回溯并找出原因。

也...

您在代码中使用文字键串会产生静默运行时错误。输入错误不会被编译器捕获。象征性地定义字符串。更好的是,创建自己的自定义NSManagedObject子类,并且可以使用常规的setter / getter而不是valueForKey:

如果第一次通话失败,您第二次在上下文中调用-save:。这不太可能有所帮助。考虑将error.localizedDescription放入labelStatus.text而不是单词"错误"。

我可能会测试各个字段中文本的长度是否大于0,而不是与@""进行比较。它更短,更容易阅读。另请参阅https://www.bignerdranch.com/blog/isequal-vs-isequaltostring/,原因有两个:isEqualToString:

答案 3 :(得分:0)

除了Hal Mueller要检查的事项清单外,我还要添加......

如果我要在大多数情况下检查isEqual: @"",我也会检查isEqual: nil ...

使用你的例子......

if ([self.txtfFirstName.text isEqual: @""] || 
    [self.txtfFirstName.text isEqual: nil] || 
    [self.txtfLastName.text isEqual: @""] || 
    [self.txtfLastName.text isEqual: nil] || 
    [self.txtfPhoneNumber.text isEqual: @""] || 
    [self.txtfPhoneNumber.text isEqual: nil] || 
    [self.txtfUserEmail.text isEqual: @""] || 
    [self.txtfUserEmail.text isEqual: nil]) {