NSPredicate - filtering values based on a BOOLEAN stored value

后端 未结 8 972
终归单人心
终归单人心 2021-02-03 19:55

I have a core data model object called Entry. In this I have an attribute IsFavorite.

I would like to use an NSPredicate to filter the results of my NSFetchedResultsCont

相关标签:
8条回答
  • 2021-02-03 20:39

    swift 3 version worked great for me:

     let predicate = NSPredicate(format: "isFriend == %@" ,NSNumber(booleanLiteral: false))
    

    following @scipilot answer the bool shouldn't be an optional. thanks for that!

    0 讨论(0)
  • 2021-02-03 20:39

    Interestingly if you "know" which one you want, you can just have:

    let p = NSPredicate(format: "showMe == true")
    

    example,

    let r = NSFetchRequest<NSFetchRequestResult>(entityName: "CDThing")
    let p = NSPredicate(format: "showMe == true")
    r.predicate = p
    

    You would do this for things like "subscribed", "new" etc.

    0 讨论(0)
  • 2021-02-03 20:41

    on iOS 10, xcode 9.0, looking for a core data managedObject with Boolean NO attribute:

    [NSPredicate predicateWithFormat:@"attributeName == nil"]
    
    0 讨论(0)
  • 2021-02-03 20:42

    This isn't really specific to NSPredicate... Whenever you have %@ in a format string, the corresponding value must be a pointer to an object, and BOOL doesn't qualify. So instead of passing YES, pass [NSNumber numberWithBool: YES].


    In newer versions of Xcode and the SDKs than when I originally wrote the answer, you can use @YES instead of [NSNumber numberWithBool: YES].

    0 讨论(0)
  • 2021-02-03 20:51

    From Apple's documentation:

    Boolean Values

    You specify and test for equality of Boolean values as illustrated in the following examples:

    NSPredicate *newPredicate =
        [NSPredicate predicateWithFormat:@"anAttribute == %@", [NSNumber numberWithBool:aBool]];
    NSPredicate *testForTrue =
        [NSPredicate predicateWithFormat:@"anAttribute == YES"];
    

    However, something that caught me out:

    Be sure to untick the Optional entity attribute and set a Default Value of YES or NO, otherwise the column will be empty (null?) and the above predicates will not match rows which are not explicitly set.

    I used the great app sqllitebrowser to diagnose this one, by looking at the resulting simulator database.

    0 讨论(0)
  • 2021-02-03 20:51

    If you know you're looking for a YES (and therefore don't need to switch between YES or NO in different situations), this worked for me:

    [NSPredicate predicateWithFormat:@"isFavorite == 1"]
    
    0 讨论(0)
提交回复
热议问题