Search code examples
iosparse-platformswift2xcode7pfquery

Getting a boolean value from a parse object and performing a if/else statement on it in Xcode 7, Swift 2


The title says it all. I have read through the Parse docs and it is just going right over my "new to coding" brain. How do I get a parse Boolean object, which i already have created, and perform a if/else statement on based on whether it is true or not?

Thank you


Solution

  • I use obj-c, not Swift, so I can't help you with syntax, but in iOS, you need to store/retrieve parse booleans as NSNumbers. So storing a boolean:

    [myPFObject setObject:[NSNumber numberWithBool:myBool] forKey:@"myKey"];
    

    for retrieving that object and using it as an if/else condition:

    NSNumber *boolNumber = [myPFObject objectForKey:@"myKey"];
    bool myBool = boolNumber.boolValue;
    if( myBool )
    ...
    

    Obviously, being able to do so depends on having properly saved / fetched your object from parse, which throws a lot of people off because it's synchronous, as in multi threaded. Say you call fetch on your object, then immediately try to access that bool value. You won't be able to, because the fetch happens on a separate thread, and your main thread immediately goes to the next line you try to access it. You need to be using the fetch/saveInBackgroundWithBlock methods of PFObjects, and doing whatever you need to do with the values inside of the callback, rather than outside.