I am doing something like this:
// GET THE USER ID
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *user_id = [standardUserDefaults objectForKey:@"user_id"];
And then checking whether the user_id is empty
if ([user_id length] == 0) {
proceed = false;
NSLog(@"Error: User id is not set.");
}
And I get this runtime exception:
* Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘-[__NSCFBoolean length]: unrecognized selector sent to instance 0x1469f70’
Any idea why I get the exception? I didn’t think there was anything too wrong with what I was doing.
Thanks!
This:
Is returning an
NSNumber(asNSCFBooleanis a private subclass ofNSNumber) rather than a string. It therefore doesn’t implementlength, causing the exception.Perhaps you want to test
[user_id intValue] > 0? Even if you convert it to a string it’ll always have some length.(side issues raised: merely declaring
user_idas a reference to anNSStringdoesn’t mean that anything you assign to it magically becomes a string; indeed there are no type object-type coercion effects whatsoever. The compiler doesn’t complain because theNSUserDefaultsreturn objects of typeid, i.e. it guarantees they’re objects but makes no claims as to their type, and the compiler doesn’t know either. All objects may be cast to and fromidwithout generating a warning, so that it can be used by classes such as the user defaults,NSArray, etc, where they can accept anything as long as it’s an object).EDIT: based on issues raised in the comments, it sounds like the thing originally being stored may not be a string. A good way to validate web stuff is probably something like: