27

How do I wrap a BOOL in an object type in Objective-C?

I want to store a BOOL in the userInfo object of an NSTimer. How do I wrap it?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Shade
  • 9,936
  • 5
  • 60
  • 85

1 Answers1

35
NSNumber *boolForUserInfo = @YES; // or [NSNumber numberWithBool:YES] the old way
[userInfo setObject:boolForUserInfo forKey:@"myBool"];

Retrieve with:

[[userInfo objectForKey:@"myBool"] boolValue];
Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • As far as I know, your 'old way' is the best way to make an NSNumber from a BOOL if you're wrapping a variable and not a literal. – JordanC Apr 29 '15 at 20:36
  • 2
    @JordanC you can use literal boxing syntax like `@(myScalarVar)` to make `NSNumber` from either simple `BOOL` or some `NSInteger`. – Eimantas Apr 30 '15 at 06:51