NSPredicate predicateWithFormat用于电子邮件问题

时间:2015-12-30 06:33:31

标签: ios core-data nspredicate nsfetchrequest predicatewithformat

我面临使用predicateWithFormat方法创建NSPredicate类型对象的问题。

AppDelegate *appdelegateObj = (AppDelegate *)[[UIApplication sharedApplication] delegate];

self.managedObjectContext = [appdelegateObj managedObjectContext];
NSString *emailWithBackslashedAtTheRate = [email stringByReplacingOccurrencesOfString:@"@" withString:@"\\@"];

NSFetchRequest *fetchRequestObj = [NSFetchRequest fetchRequestWithEntityName:@"Usertable"];
NSMutableArray *dataList;

**NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"email CONTAINS[c] %@",emailWithBackslashedAtTheRate]];**
[fetchRequestObj setPredicate:predicate];

@synchronized(delegate.persistentStoreCoordinator) {

    NSError *error = nil;
    NSMutableArray *filteredUser = (NSMutableArray *)[self.managedObjectContext executeFetchRequest:fetchRequestObj error:&error];
}

任何人都可以解释,问题是什么?

2 个答案:

答案 0 :(得分:2)

在您的Usertable中,字段名称电子邮件必须是字符串。enter image description here

 AppDelegate *coreAppDelegate=[[UIApplication sharedApplication]delegate];
        NSManagedObjectContext *context=[coreAppDelegate managedObjectContext];
        NSEntityDescription *entityDecs=[NSEntityDescription entityForName:@"UserDetail" inManagedObjectContext:context];
        NSFetchRequest *request =[[NSFetchRequest alloc]init];
        [request setEntity:entityDecs];
        //  NSLog(@"username = %@",mutarr);
        NSPredicate *pred=[NSPredicate predicateWithFormat:@"(email=%@)",TxtEmail];
        [request setPredicate:pred];
        NSManagedObject *matches =nil;
        NSError *error;

答案 1 :(得分:0)

您不能使用NSString方法stringWithFormat来构建用于谓词的格式字符串。尽管名称相似,但predicateWithFormatstringWithFormat的工作方式不同。您应该将正确的格式字符串直接传递给predicateWithFormat

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"email CONTAINS[c] %@", email];

(此实例的主要区别在于predicateWithFormat用单引号括起%@表示的字符串,而stringWithFormat则不包含。)