开发者

Get all items starting with a given string

开发者 https://www.devze.com 2023-03-10 18:58 出处:网络
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 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.


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:

NSString               *str            = [NSString stringWithFormat:@"%@ beginswith \"%@\"", fieldName, titleTerm];
NSPredicate            *predicate      = [NSPredicate predicateWithFormat:str];

The content was having wrong quotation wrappings.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号