How to use binary flags in Core Data?

前端 未结 4 1852
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 14:35

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 NSPre

4条回答
  •  误落风尘
    2020-12-24 14:35

    Here is one example / application of this technique.

    Say you have a NSManagedObject that has an integer attribute with the keypath "typeValue".

    Somewhere in your code define a bitwise enumeration:

    typedef enum SomeType {
        SomeTypeValueOne = 0x1,
        SomeTypeValueTwo = 0x2,
        SomeTypeValueThree = 0x4
    } SomeType;
    

    Now to query for managed objects that are of type say One or Three but not Two, do the following:

    SomeType valueOneOrThree = SomeTypeValueOne | SomeTypeValueThree;
    
    NSPredicate *someTypePredicate = [NSPredicate predicateWithFormat:@"(typeValue & %i) == typeValue", valueOneOrThree];
    
    // construct NSFetchRequest as normal with predicate...
    

提交回复
热议问题