mgcleveland
mgcleveland

Reputation: 133

Can you evaluate the contents of an NSString and get the BOOL value of the evaluated expression?

In Objective-C, say you have an NSString containing the following:

NSString * boolStr = [NSString stringWithFormat:@"%@", "1 > 0"];

Is there a way to evaluate the NSString and get the boolean value of the string's contents?

Upvotes: 1

Views: 219

Answers (1)

Gerd K
Gerd K

Reputation: 2993

I assume you want to evaluate an actual expression. For simple expressions you can abuse NSPredicate to do that, example:

    NSPredicate *predicate1=[NSPredicate predicateWithFormat:@"1>0"];
    NSPredicate *predicate2=[NSPredicate predicateWithFormat:@"1<0"];

    BOOL    ok1=[predicate1 evaluateWithObject:nil];
    BOOL    ok2=[predicate2 evaluateWithObject:nil];

    NSLog(@"ok1: %d  ok2: %d",ok1,ok2);

This will print: ok1: 1 ok2: 0

Upvotes: 3

Related Questions