0

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?

2 Answers2

1

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;
}
Wain
  • 118,658
  • 15
  • 128
  • 151
  • is there by anymeans that I could insert NSNull instead of ? –  May 30 '16 at 07:32
  • You already are returning that instance, but you can't change the description it returns, you need to return a string instead – Wain May 30 '16 at 07:37
  • Ca you please explain with reference to my code? Thank you –  May 30 '16 at 08:09
  • I'm not sure why you want to return that string but I've updated the answer – Wain May 30 '16 at 10:16
  • It works. Thank you. I replaced @"NSNull" with "null" –  May 30 '16 at 11:05
0

try this

change the type anyobject id to NSNumber *

 - (NSNumber *)NSNullToNilForKey:(NSNumber *)number
{
    if ([[number stringValue] length] == 0){
        return [NSNull null];
    }
    return number;
}
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143