Problems with adding objects to NSMutableDictionary

↘锁芯ラ 提交于 2019-12-01 23:13:49

问题


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.


回答1:


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 :)




回答2:


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];
}



回答3:


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??



来源:https://stackoverflow.com/questions/8658448/problems-with-adding-objects-to-nsmutabledictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!