Question

I'm trying to debug a strange problem I'm seeing when passing a NSDictionary as my userInfo in NSNotification using ARC on ios 6. Here's my relevant code:

to send the notification:

NSDictionary *feedData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];

NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys:@"index", [NSNumber numberWithInt:i], @"myKey", feedData, nil];

[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object: nil userInfo:finalData];

my handler registration:

[[NSNotificationCenter defaultCenter] addObserver:frcvc selector:@selector(mySelector:) name:@"myNotification" object:NULL];

my handler declaration:

-(void)mySelector:(NSNotification*)notification;

my handler definition which is inside my MyCollectionViewController class:

- (void)mySelector:(NSNotification*) notification
{
    NSDictionary* myDict = (NSDictionary*)notification.userInfo;
    int index = [[myDict objectForKey:@"index"] integerValue];
    NSDictionary* myFeed = (NSDictionary*)[myDict objectForKey:@"myKey"];
}

When I run the code, I can see finalData being constructed, and I make note of the memory address. When I get to my callback and extract userInfo, it is the same memory address, but xcode seems to think it is of type MyCollectionViewController*. And when I try to access index or myFeed, it is null. But in my output window, I can type

"p myDict"

and it correctly shows NSDictionary* with the same memory address as when constructed! And if I type

"po myDict"

it shows the correct dictionary keys and values! What is going on?! I've tried rebuilding clean, but that didn't help. The memory seems to be fine, since I'm getting the correct address and can seem to access it in the debug window. Thanks for any help!

Was it helpful?

Solution

Your objects and keys are in the wrong order:

NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys:@"index", [NSNumber numberWithInt:i], @"myKey", feedData, nil];

It should be:

NSDictionary* finalData = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:i], @"index", feedData, @"myKey", nil];

Or even better, using Objective-C Literals:

NSDictionary* finalData = @{@"index": [NSNumber numberWithInt:i], @"myKey": feedData};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top