Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use binary flags in Core Data?

Tags:

I have an int32 attribute in a Core Data database. I use this int as an enum bit field.

Is it possible to create a NSPredicate to query items based on the binary value of this int ? Something like @"bitFieldAttribute & 0x0001"?

I'm also wondering if this is possible with a binary typed attribute ?

like image 804
CodeFlakes Avatar asked Jan 17 '11 18:01

CodeFlakes


1 Answers

NSPredicate can handle it, but I'm not sure if CoreData will accept it as a valid predicate for execution on a data store. It might have trouble converting the bitwise operator into a SQL query (if you're using a SQLite backing store). You'll just have to try it.

The syntax, however, is just what you'd expect:

NSPredicate * p = [NSPredicate predicateWithFormat:@"(3 & 1) > 0"]; NSLog(@"%@", p); NSLog(@"%d", [p evaluateWithObject:nil]); 

Logs:

3 & 1 > 0 1 

As for doing this on a binary-typed attribute (ie, one defined as data, right?) This probably won't work. Bitwise operators only really make sense when operating on integers (insofar as I understand them), so executing it on an NSData wouldn't make much sense. Convert it to a number first, and then it might work.

edit

It would appear that SQLite supports this syntax, since bitwise operators have been around since 2001, which means that Core Data will probably accept it as well.

like image 90
Dave DeLong Avatar answered Sep 22 '22 15:09

Dave DeLong