【问题标题】:NSPredicate predicateWithFormat for email issue用于电子邮件问题的 NSPredicate predicateWithFormat
【发布时间】:2015-12-30 06:33:31
【问题描述】:

我在使用 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];
}

谁能解释一下,是什么问题?

【问题讨论】:

  • 通过调用executeFetchRequest返回的error是什么?
  • emailWithBackslashedAtTheRate 的格式是什么,您的实体中的 email 属性名称是什么?
  • 你能记录下是什么问题吗?
  • 无法解析格式字符串“(email=iostest1@gmail.com)”

标签: ios core-data nspredicate nsfetchrequest predicatewithformat


【解决方案1】:

在您的用户表中,字段名称电子邮件必须是字符串。

 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;

【讨论】:

    【解决方案2】:

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

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

    (此实例的主要区别在于predicateWithFormat 将由 %@ 表示的字符串括在单引号中,而stringWithFormat 没有。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-02
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-22
      • 2019-05-18
      相关资源
      最近更新 更多