使用NSPredicate包含在coredata实体的字段中查找字符

Mik*_*e S 5 iphone core-data nspredicate ios4

我正在尝试找到包含特定字母序列的所有客户.我想要与NSString的rangeofString相同的功能,除了不区分大小写.继承我的方法:

-(NSArray *) db_search: (NSString *) table where: (NSString*) fieldKey contains: (NSString*) value withSortField: (NSString *) sortField{
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    NSEntityDescription *entity = [NSEntityDescription entityForName:table inManagedObjectContext:context];
    if (fieldKey != nil){
        NSPredicate *predicate = [NSPredicate
                                  predicateWithFormat:@"(%@ contains[c] %@)",
                                  fieldKey,value];
        [request setPredicate:predicate];
    }
    [request setEntity:entity];

    if (sortField != nil){
        NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:[self extractSortField:sortField] ascending:[self isAscending:sortField]] autorelease];
        NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor, nil] autorelease];
        [request setSortDescriptors:sortDescriptors];
    }

    NSError *error;
    return [context executeFetchRequest:request error:&error];
}
Run Code Online (Sandbox Code Playgroud)

我用这些值来称呼它:

NSArray * results = [self db_search:@"Customer" where:@"fullname" contains:@"matt" withSortField:nil];
Run Code Online (Sandbox Code Playgroud)

而不是得到所有Matts,Matthews等,当我试图打印出结果时,它会冻结.我调试了它,我们甚至没有得到一个空的NSArray.我打印NSArray到控制台,我没有得到0元素..我什么都没得到.

我已经尝试将数据库转储到控制台,它包含所有正确的东西.救命!!!

= UPDATE ================================================ ======

我正在使用%K,我得到一个奇怪的运行时错误:

if (searchResults1 != nil){
    NSLog(@"%Matches: %i", [searchResults1 count]);
}else {
    NSLog(@"Was NULL");
}
Run Code Online (Sandbox Code Playgroud)

它在NSLog上(@"%匹配:行.它是一个坏的EXC错误.所以searchResults1不是nill但是当我尝试读取计数时崩溃?当我调试时,searchResults1确实是一个NSArray但它似乎没有里面有什么东西.

Dav*_*ong 13

看起来您的问题是您的谓词:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ contains[c] %@)", fieldKey,value];
Run Code Online (Sandbox Code Playgroud)

当您在传递fieldKey = @"fullname"value = @"matt",这个谓词将是等效于:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"('fullname' contains[c] 'matt')"];
Run Code Online (Sandbox Code Playgroud)

你看到了问题吗?它将"fullname"视为原始字符串,而不是字段的名称.这是因为您%@在格式字符串中使用修饰符.当NSPredicate遇到这些时,它会说"啊哈!在这里取代的价值将是一个常数".你真正想要它做的是说"啊哈!这里取代的价值将是一个标识符".

所以不要使用%@,请使用%K.这是一个仅用于谓词的特殊修饰符,它意味着在字符串中替换为标识符(实际上是"keypath"),这意味着它将使您的谓词为:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(fullname contains[c] 'matt')"];
Run Code Online (Sandbox Code Playgroud)

这就是你要找的东西.


Mik*_*e S 0

我忘记在我的辅助方法之一中返回 NSArray。