Search code examples
iosnsnotificationcenter

Notification crashes application


I am trying to pass NSMutableDictionary to NSNotification to other class. But when releasing NSMutableDictionary application crashes. can any one help? I am trying this

NSMutableDictionary *temp = [[NSMutableDictionary alloc]init];

NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
temp =  [responseString JSONValue];
NSLog(@"webdata is %@",temp);
NSLog(@"inside usersignup success");
[[NSNotificationCenter defaultCenter] postNotificationName:CNotifySignupSucess object:temp];
[temp release];

Solution

  • First of all, you need to read some iOS programming basics. And,

    NSMutableDictionary *temp = [[NSMutableDictionary alloc]init];
    
    NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
    temp =  [responseString JSONValue]; //----> this line is wrong
    

    because, temp pointer points to the newly created NSMutableDictionary object, the you are reassigning it to another object returned by JSONValue method, which is autorelease object, and you don't own it, thus can't release it. Some better ways to achieve want you want would be:

    NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
        NSMutableDictionary *temp =  [responseString JSONValue];
        NSLog(@"webdata is %@",temp);
        NSLog(@"inside usersignup success");
        [[NSNotificationCenter defaultCenter] postNotificationName:CNotifySignupSucess object:temp];
        //NO RELEASING the AUTORELEASE OBJECT!!!!
    

    OR:

    NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
        NSMutableDictionary *temp = [[NSMutableDictionary alloc]initWithDictionary:[responseString JSONValue]];
        NSLog(@"webdata is %@",temp);
        NSLog(@"inside usersignup success");
        [[NSNotificationCenter defaultCenter] postNotificationName:CNotifySignupSucess object:temp];
        [temp release];
    

    OR:

    NSMutableDictionary *temp = [[NSMutableDictionary alloc]init];
    
        NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
        [temp addEntriesFromDictionary:[responseString JSONValue]];
        NSLog(@"webdata is %@",temp);
        NSLog(@"inside usersignup success");
        [[NSNotificationCenter defaultCenter] postNotificationName:CNotifySignupSucess object:temp];
        [temp release];
    

    In the last 2 cases I'm considering that JSONValue method returns NSDictionary. Goog Luck!