Vedaant Arora
Vedaant Arora

Reputation: 217

Problems with adding objects to NSMutableDictionary

I am making an iPhone app and I am loading information from a server. I send NSURLRequest to the server and get back a NSString value. This is working fine and the value I am getting back is the correct one. The problem is that when I try to add the value for the variable to a NSMutableDictionary I have made to store the values, it doesn't work. When I debug and look at the values of the NSMutableDictionary in Xcode it says 0 key/value pairs right after the line where I add the values. This is what my code looks like:

    NSArray *varsToLoad = [fixedData objectForKey:@"varsToLoad"];
    NSError *error;
    for(NSString *var in varsToLoad){
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: someURL]];
        [request setHTTPMethod:@"POST"];
        NSMutableString *file = [NSMutableString stringWithString:@"file="];
        NSString *file1 = [file stringByAppendingString:var];
        NSString *file2 = [file1 stringByAppendingString:@".txt"];
        [request setHTTPBody:[file2 dataUsingEncoding:NSUTF8StringEncoding]];
        NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
        NSString *value = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        [varsLoaded setObject:value forKey:var];
    }

varsLoaded is declared at the @implementation and is a NSMutableDictionary.

Upvotes: 3

Views: 1021

Answers (3)

ennuikiller
ennuikiller

Reputation: 46965

You should really check the response before processing any further. Wrap it in something like this:

if (response == nil) {
    // Check for problems

}
else {
     NSString *value = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
        [varsLoaded setObject:value forKey:var];
}

Upvotes: 0

aslı
aslı

Reputation: 8914

The problem may be that you haven't initialized your varsLoaded by saying self.varsLoaded = [NSMutableDictionary dictionary];

So you're adding objects to a non-existing dictionary, but you're not getting an exception because this is normal in objective-c :)

Upvotes: 3

Michael Dautermann
Michael Dautermann

Reputation: 89509

Change the first line of your code from NSArray to NSMutableArray and see if you have better luck.

It doesn't matter that you declared your varsLoaded as a NSMutableDictionary somewhere else... in the local context of that code above, the compiler believes varsToLoad is a immutable array and probably isn't even compiling your setObject: forKey: line. You're not getting warnings in the build log or in the console while you're running??

Upvotes: -1

Related Questions