Adding NSMutableArray to NSMutableDictionary and the arrays are null?
I've got a simple object "post" that has two NSMutableArrays
as properties. One is for "image" objects and the other is for "video" objects. At some point in the lifecycle of "post", I ask it for a dictionary representation of itself.
NSMutableDictionary *postDict = [post getDictionary];
-(NSMutableDictionary *)getDictionary{
NSMutableArray *imgDictArry = [NSMutableArray arrayWithObjects:nil];
NSMutableArray *movDictArry = [NSMutableArray arrayWithObjects:nil];
for (int i = 0; i<self.images.count; i++) {
NSMutableDictionary *imgDict = [[self.images objectAtIndex:i] getDictionary];
[imgDictArry addObject:imgDict];
}
for (int i = 0; i<self.videos.count; i++) {
NSMutableDictionary *movDict = [[self.videos objectAtIndex:i] getDictionary];
[movDictArry addObject:movDict];
}
NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:self.friendsOnly], @"IsFriendsOnly",
self.message, @"Message",
self.shortText, @"ShortText",
self.authorId, @"AuthorId",
self.recipientId, @"RecipientId",
self.language, @"Language",
self.lat, @"Lat",
self.lng, @"Lng",
imgDictArry, @"Images",
movDictArry, @"Videos",
nil];
return postDict;
}
As you can see, the "image" and "video" objects have their own methods for describing themselves as NSMutableDictionary
objects.
-(NSMutableDictionary *)getDictionary{
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
开发者_高级运维 self.nativeURL, @"NativeURL",
self.previewURL, @"PreviewURL",
self.smallURL, @"SmallURL",
self.thumbURL, @"ThumbURL",
self.imageId, @"ImageId",
self.width, @"Width",
self.height, @"Height",
nil];
}
I'm not getting any errors but my imgDictArry
and movDictArry
objects are turning out to be NULL
after I've set them on the postDict
object. If I log them to the console just before this moment, I can see the dictionary data. But the other classes requesting this object is getting null for those properties.
Perhaps one of your functions such as self.shortText
(or self.lat
...) is returning nil
, in which case dictionaryWithObjectsAndKeys
isn't what you expect it to be: it's truncated to the first function that returns nil
...
I changed the postDict creation to this...
NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:self.friendsOnly], @"IsFriendsOnly",
self.message, @"Message",
self.shortText, @"ShortText",
self.authorId, @"AuthorId",
self.recipientId, @"RecipientId",
self.language, @"Language",
self.lat, @"Lat",
self.lng, @"Lng",
nil];
[postDict setObject:imgDictArry forKey:@"Images"];
[postDict setObject:movDictArry forKey:@"Videos"];
and it's fixed. But I don't know why.
精彩评论