vendredi 18 septembre 2015

Unable to save Object(s) to CoreData

I have a data model with an entity of HYUser and the attributes of firstName, lastName, email, gender and phone. When I check my .sqlite DB, nothing is there. I have attached my entire button action that should save my object.

- (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";

    }
}
}

Aucun commentaire:

Enregistrer un commentaire