简体   繁体   中英

Objects, boolean logic, and boxing nil in Objective-C

I would like to return an NSDictionary which might contain an NSError value for one key, and if not, should contain a null value. I know that I cannot actually set a value to nil because it is not an object, but why can I not use the || operator to return NSNull if my NSError is nil?

if (requestError || ![matches count]) {
    return @{@"success": @NO,
             @"error": requestError || [NSNull null],
             @"country": country};
}

The error I get is Collection element of type 'int' is not an Objective-C object . I understand that nil is an int value, but why does nil || NSObject nil || NSObject not guarentee that an NSObject will be returned?

The || operator returns a boolean, so requestError || [NSNull null] requestError || [NSNull null] returns YES or NO . You could use the ternary operator instead:

@"error": requestError ? requestError : [NSNull null],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM