我试图将我的字段存储在无法存储的核心数据中

时间:2016-02-03 17:17:12

标签: ios objective-c core-data

在我的代码中,我使用简单的注册页面。这些字段是名字,姓氏,电子邮件,密码和phoneno。因为如果我注册一个新成员意味着新存储的电子邮件ID已经存储意味着它不能存储在核心数据中。这是我的条件。

这是我的代码,

//Appdelegate call

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];  

NSManagedObjectContext *context = [appDelegate managedObjectContext];

//Fetch Request

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Device"
                                              inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc]init];

[request setEntity:entityDesc];

NSLog(@"Your Request is : %@",request);

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(email = %@)", email];

[request setPredicate:pred];

NSError *error=nil;
NSArray *result = [context executeFetchRequest:request error:&error];

NSLog(@"Your Result is: %@",result);


if ([result count] > 0){

    if ([email isEqual:[[result valueForKey:@"email"]lastObject]])
    {
        [alertView AlreadyRegisterAlertView];
    }
    else{

        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];

        NSLog(@"Welcome for Register Section");

        [newDevice setValue:nameFile.fname forKey:@"fname"];
        [newDevice setValue:nameFile.surname forKey:@"sname"];
        [newDevice setValue:nameFile.eid forKey:@"email"];
        [newDevice setValue:nameFile.phone forKey:@"phone"];
        [newDevice setValue:nameFile.passd forKey:@"password"];
        [newDevice setValue:nameFile.imgProfile forKey:@"photo"];


        [alertView RegistrationSucessAlertView];

        NSLog(@"Your First Name is: %@",nameFile.fname);
        NSLog(@"Your Sur-Name is: %@",nameFile.surname);
        NSLog(@"Your Email id is: %@",nameFile.eid);
        NSLog(@"Your Phone Number is: %@",nameFile.phone);
        NSLog(@"Your Password is: %@",nameFile.passd);
        NSLog(@"Your Profile Image is: %@", nameFile.imgProfile);
    }

}

// Save the object to persistent store

if (![context save:&error]) {

    NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}

在此代码中,条件if([result count]>0)为false,表示我该怎么做。

1 个答案:

答案 0 :(得分:0)

我看到的问题是在这一行

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(email = %@)", email];

代码应该是

NSPredicate *pred = [NSPredicate predicateWithFormat:@"email == %@", email];


更新

首先,我认为逻辑是不正确的。您正在尝试在实际保存之前获取核心数据对象。您必须插入新实体并将其保存到核心数据。然后,如果需要,您必须获取对象以进行任何进一步处理。

这就是为什么你的if条件每次都失败的原因。