Search code examples
objective-ccocoa-touchnsdictionarynsnull

NSMutableDictionary and [NSNull null] values


Ok. I've searched and searched to no avail and I keep beating my head over this.

I'm trying to determine if a UITextField has a blank value, and if so send a null value up to the server, rather than just a blank string.

The following code

NSDictionary *locationDict = @{
    @"country":countryVal,
    @"state":stateVal,
    @"city":[cityField.text isEqualToString:@""] ? [NSNull null] : cityField.text
};
NSLog(@"%@", locationDict);

logs this

{
    city = "<null>";
    country = US;
    state = TN;
}

I cannot figure out why [NSNull null] gets logged at "<null>". The app keeps sending that string up as the city if the user doesn't enter a value, obviously not what I was going for. I'm not showing the network call here, but I'm using AFNetworking to do this. I can confirm that the dictionary contains that string instead of null before I ever call AFN, though. So I know the problem doesn't lie with AFN.

Any help is greatly appreciated.


Solution

  • <null> is the result of [[NSNull null] description]. You can see this for yourself with NSLog(@"%@", [NSNull null]);. If you want something other than <null> when the user doesn't enter a city, use the value you want instead of [NSNull null] in your line @"city":[cityField.text isEqualToString:@""] ? [NSNull null] : cityField.text.