Question

I think my error has to do with me not implementing my NSDictionary properly. Below is the error code I'm getting.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary bytes]: unrecognized selector sent to instance 0x16eab400'

The error happens in the following method:

- (void)check:(NSData *)json{ 
NSDictionary *json1 = [NSJSONSerialization
                     JSONObjectWithData:json
                      options:kNilOptions
                      error:nil];

NSUserDefaults *userdefaluts = [NSUserDefaults standardUserDefaults];
[userdefaluts setObject:[json1 objectForKey:@"Name"] forKey:@"name"];
[userdefaluts setObject:[json1 objectForKey:KEY_USER_ID] forKey:KEY_USER_ID];

NSLog(@"MainView - check - name: %@",[userdefaluts objectForKey:@"name"]);
NSLog(@"MainView - check - name: %@",[userdefaluts objectForKey:KEY_USER_ID]);
}
Was it helpful?

Solution 3

So the answer was quite easy. All I had to do was change the data type coming in to NSDictionary. Below is the correct code.

- (void)check:(NSDictionary *)json{ 
NSDictionary *json1 = [NSJSONSerialization
                 JSONObjectWithData:json
                  options:kNilOptions
                  error:nil];

NSUserDefaults *userdefaluts = [NSUserDefaults standardUserDefaults];
[userdefaluts setObject:[json1 objectForKey:@"Name"] forKey:@"name"];
[userdefaluts setObject:[json1 objectForKey:KEY_USER_ID] forKey:KEY_USER_ID];

NSLog(@"MainView - check - name: %@",[userdefaluts objectForKey:@"name"]);
NSLog(@"MainView - check - name: %@",[userdefaluts objectForKey:KEY_USER_ID]);
}

OTHER TIPS

Possibilities: Your code might run on a background thread and NSUserDefaults doesn't like it. One of the objectForKey calls on json1 returns nil and things go wrong. I'd store the two [json1 objectForKey:...] results in a local variable and NSLog them. Step through the code in the debugger step by step.

And the big possibility: The object "json" that you are passing in isn't actually NSData. Do an NSLog on it and check what it really is. It might be an NSDictionary* and not an NSData*, which would explain why a method used for NSData (length) is sent to an NSDictionary. Check the call to the method. Are you passing an object of type "id"?

Your data is probably wrong and NSJSONSerializer cannot parse it, try this to show if there is an error : NSError *jsonError; NSDictionary *json1 = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:&jsonError]; if(jsonError){ NSLog(@"could not parse json data, error : %@",jsonError.localizedDescription); }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top