0

I´m a beginer and have lately got a great deal of trouble with this issue. I want to pass a NSDictnonary Data to a server from my app and in some cases if the user hasen´t chosen any option I want to remove nil objects. I have looked into this thread that seems be the right method but I haven't succeed to implement in my code. How to remove a null value from NSDictionary

My guess would be to implement the code to Null directly in my NSDictonary Here´s my Dictionary code

     -(NSDictionary*)parametersForCreateActivities

   {
    NSString *token = [[A0SimpleKeychain keychain] stringForKey:tokenConstant];
    NSString *userId = [[A0SimpleKeychain keychain] stringForKey:child_id];
    NSString *userCreate = [[NSUserDefaults standardUserDefaults] objectForKey:@"CreateTitle"];
    NSString *createDescription = [[NSUserDefaults standardUserDefaults] objectForKey:@"DescriptionText"];
    NSString *createTimestart = [[NSUserDefaults standardUserDefaults] objectForKey:@"TimeStartString"];
    NSString *createTimestop = [[NSUserDefaults standardUserDefaults] objectForKey:@"TimeStopString"];
    NSString *createImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"DefaultcreateImageID"];

    NSDictionary *parameters;
    if (userId && token) {
        parameters = @{child_id: userId, tokenConstant:token, activity_name    :userCreate, create_Description :createDescription, create_Timestart :createTimestart, create_Timestop :createTimestop, create_Image :createImage};

    }
    return parameters;
}

My guess is that It should check somewhere in the code for nil objects and remove theme. But I have really struggled with figuring out how to format the code. I´m guessing the code should be something like this but I have no idea where to place it and how to format it.

NSMutableDictionary *dict = [parametersForCreateActivities mutableCopy];
NSArray *keysForNullValues = [dict allKeysForObject:[NSNull null]];
[dict removeObjectsForKeys:DefaultcreateImageID];
Community
  • 1
  • 1

1 Answers1

0

Try below code

NSMutableDictionary *yourDictionary; // Your dictionary object with data

NSMutableDictionary *updatedDic = [yourDictionary mutableCopy];
for (NSString *key in [yourDictionary allKeys]) {
    if ([yourDictionary[key] isEqual:[NSNull null]] || [yourDictionary[key] isKindOfClass:[NSNull class]]) {
        updatedDic[key] = @"";
    }
}
yourDictionary = [updatedDic copy];
NSLog(@"%@",yourDictionary);
Nilesh Patel
  • 6,318
  • 1
  • 26
  • 40
  • I tried you solution but I´ll get the error message initWithObjects:forKeys:count:]: attempt to insert nil object from objects[6]' – Anton Håkanson Mar 19 '16 at 12:21