Reputation: 2270
I have a core data table called Forms which contains a attribute called objectids which holds a comma separated string with ids. (it can also contain just one id) ex.
objectids = "90" // one id
objectids = "91,23,44" // multiple ids
I receive a objectid and I want to match that and see if it exists as a value in any Forms -> objectids entry.
What is important is that it only matches whole string. ie. objectid: 1 should not match with objectids: 91, 23, 44, etc.
Here is a snippet of my code.
-(NSDictionary*)readForm:(NSString*)objectid
{
...
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Forms"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"added_date" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[fetchRequest setReturnsObjectsAsFaults:NO];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userid == %@ AND objectids == %@ AND active == %@", user.userid, objectid, @"yes"];
// *** in this fetchRequest I want to include some snippet of code to:
// *** Match string, but only whole string seperated by commas, unless it only has one value in which case it contains no commas.
NSError *err = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&err];
if([results count])
{
...
}
}
I hope it's understandable.
I simply do not know enough of objective C to even know what terms to search for.
Any help is appreciated!
Upvotes: 1
Views: 2159
Reputation: 103
Considering your example:
objectids = "90" // one id
objectids = "91,23,44" // multiple ids
In case there's only 1 id, you can compare the full string. In case there are more ids, they are always either preceded or followed by a comma.
Perhaps you can use something like this:
NSString *first = [NSString stringWithFormat:@"%@,%%", objectid];
NSString *last = [NSString stringWithFormat:@"%%,%@", objectid];
NSString *inBetween = [NSString stringWithFormat:@"%%,%@,%%", objectid];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userid == %@ AND (objectids == %@ OR objectids LIKE %@ OR objectids LIKE %@ OR objectids LIKE %@) AND active == %@", user.userid, objectid, first, last, inBetween, @"yes"];
Which should make a statement like:
Upvotes: 1
Reputation: 1144
For string comparisons, you could use LIKE instead of ==, and also, for your bool, use a literal, @YES, so your predicate would be :
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"userid == %@ AND objectids LIKE %@ AND active == %@", user.userid, objectid, @YES];
For more complex string comparisons, you could use a predicateWithBlock:
EDIT : reading your further comments, I think this question answers the exact same problem using regex : Form NSPredicate from string that contains id's
Upvotes: 2