Handling CFNull Objects in NSPropertyListSerialization

In my application, I am trying to serialize a server response dictionary and write it to the file system. But I get the error "The property list is not valid for the format" for some answers. The reason is the CFNull objects in the server response. Now the server’s response will change, so I don’t have a specific way to delete CFNull () objects. Below is my code:

NSString *anError = nil; NSData *aData = [NSPropertyListSerialization dataFromPropertyList:iFile format:NSPropertyListXMLFormat_v1_0 errorDescription:&anError]; 

What is the best way to solve this problem? How can I remove all CFNull objects from a server response in a single snapshot?

+4
source share
4 answers

I switched to the NSKeyedArchiver option. A bit slower than NSPropertyListSerialization, but takes care of NSNull / CFNull objects.

+4
source

I had a problem getting a response from the Facebook SDK, so I implemented this method:

 - (void)cleanDictionary:(NSMutableDictionary *)dictionary { [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (obj == [NSNull null]) { [dictionary setObject:@"" forKey:key]; } else if ([obj isKindOfClass:[NSDictionary class]]) { [self cleanDictionary:obj]; } }]; 

}

This will go through the dictionary hierarchy and turn all CFNulls into an empty string.

+9
source

I wrote a category to clear the dictionary:

 -(NSDictionary*)cleanDictionary { return [NSDictionary cleanDictionary:self]; } + (NSDictionary*)cleanDictionary:(NSDictionary *)dictionary { NSMutableDictionary *dict = [NSMutableDictionary new]; [dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (obj == [NSNull null]) { //dont add it } else if ([obj isKindOfClass:[NSDictionary class]]) { [dict setObject:[self cleanDictionary:obj] forKey:key]; } else if ([obj isKindOfClass:[NSArray class]]) { [dict setObject:[NSDictionary cleanArray:obj] forKey:key]; } else { [dict setObject:obj forKey:key]; } }]; return dict; } +(NSArray*)cleanArray:(NSArray*)array { NSMutableArray* returnArray = [NSMutableArray new]; for (NSObject *obj in array) { if (obj == [NSNull null]) { //dont add it } if ([obj isKindOfClass:[NSDictionary class]]) { [returnArray addObject:[NSDictionary cleanDictionary:(NSDictionary*)obj]]; } else if ([obj isKindOfClass:[NSArray class]]) { [returnArray addObject:[NSDictionary cleanArray:(NSArray*)obj]]; } else { [returnArray addObject:obj]; } } return returnArray; } 
+1
source

If you cannot serialize it using the datafromPropertyList:... API, then this is not a list of properties.

Either correct server responses to include the appropriate property lists, or massage the data in your application so that it can be correctly interpreted as a property list.

0
source

All Articles