Search code examples
iosobjective-cnsnull

NSNull returns <null> instead of returning null


I'm using the following code to check if a NSNumber has nil value. So I'm converting the NSNumber to string and Im checking if its length is 0. If it is of zero, Im returning NSNull else Im returning the number itself.

   - (id)NSNullToNilForKey:(NSNumber *)number
    {
        if ([[number stringValue] length] == 0){
            return [NSNull null];
        }
        return number;
    }

Im invoking it as follows,

NSString *bodyString = [NSString stringWithFormat:@"[ \"%@\",{\"session_token\": \"%@\",\"request\": [\"GetAssigneeWiseCompliancesChart\",{\"country_id\": %@,\"business_group_id\": %@,\"legal_entity_id\": %@,\"division_id\": %@,\"unit_id\": %@,\"user_id\": %@}]}]",clientSessionId,clientSessionId,[self NSNullToNilForKey:countryId],[self NSNullToNilForKey:businessGroupId],[self NSNullToNilForKey:legalEntityId],[self NSNullToNilForKey:divId],[self NSNullToNilForKey:unitId], [self NSNullToNilForKey:userId]];

But the problem is that, though the if loop is getting invoked. The value returned from the if loop of NSNullToNilForKey is <null> instead of null. How can I sort this out?


Solution

  • You're creating a string from a format, all of the parameters are added by taking their description, what you're seeing is the description of the NSNull instance.

    Your method should specifically return a string and you should choose explicitly what string you want to return.

    - (id)NSNullToNilForKey:(NSNumber *)number
    {
        if ([[number stringValue] length] == 0){
            return @"NSNull";
        }
        return number;
    }