how to save bool value in KeychainItemWrapper

2019-07-21 04:11发布

问题:

I want to store bool value in KeychainItemWrapper, how to store ?

I have tried this code, but it gives me error.

 [keychain setObject:YES forKey:(__bridge BOOL)kSecAttrIsInvisible];

回答1:

The BOOL is a primitive type and the setObject:forKey: only excepts classes that derive from NSObject.

So use NSNumber it has a special method for it + numberWithBool::

[keychain setObject:[NSNumber numberWithBool:YES] forKey:@"someKey"];

And if you need to bool again:

 NSNumber *value = [keychain objectForKey:@"someKey"];
 BOOL boolValue = [value boolValue];


回答2:

Also you can use Shorthand like

[keychain setObject:@(YES) forKey:(__bridge BOOL)kSecAttrIsInvisible];