获取以给定字符串开头的所有项目
我想获取以给定字符串开头的所有项目。
当我不使用谓词时,下面的代码会返回数千个项目,但当它存在时,我会返回零条记录。
我已经测试了 sqlite 数据库中肯定存在的字段名称和术语。
NSManagedObjectContext *context = [[DataSource sharedInstance] managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ beginswith %@)", fieldName, searchTerm, nil];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
[request setPredicate:predicate];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
[request release];
return objects;
已解决
以下解决了问题:
NSString *str = [NSString stringWithFormat:@"%@ beginswith \"%@\"", fieldName, titleTerm];
NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
内容的引号包装错误。
I want to get all items which start with a given string.
The code below returns thousands of items when I do not use the predicate, but when it is present I get zero records returned.
I have tested with field names and terms which for sure exist in the sqlite db.
NSManagedObjectContext *context = [[DataSource sharedInstance] managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:YES];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%@ beginswith %@)", fieldName, searchTerm, nil];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
[request setPredicate:predicate];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
[request release];
return objects;
Solved
The following solved the problem:
NSString *str = [NSString stringWithFormat:@"%@ beginswith \"%@\"", fieldName, titleTerm];
NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
The content was having wrong quotation wrappings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在解决自己的问题时,您应该回答自己的问题,而不是编辑问题。如果您不这样做,这个问题将显示为未回答。您可以继续并接受此答案,问题将被正确标记为已解决。
以下解决了问题:
内容的引号包装错误。
When solving your own problem you should answer your own question rather than editing the question. If you don't this question will show up as unanswered. You can go ahead and accept this answer and the question will be properly marked as solved.
The following solved the problem:
The content was having wrong quotation wrappings.