2014-10-19 66 views
0

我知道有很多类似于我的问题,但仍无法使其工作?无法更新NSMutableDictionary中的值

我有一个NSMutableDictionary,我甚至不枚举我只是想改变它的价值,但我得到的错误信息:

变异对象发送到不可变对象

这里是我得到我的字典作为参数的代码.. ,让我们把它叫做myDictionary

NSString *stringToUpdate = @"SomeString"; 
[myDictionary setObject:stringToUpdate forKey:@"time"]; 

这是我得到我的字典 GameInfo.m

 @class GameInfo; 

@interface GetData : NSObject 

@property (nonatomic, strong) NSMutableArray *gamesInfoArray; 
@property (nonatomic, strong) NSMutableDictionary *jsonDict; 


-(void) fetchData; 
-(NSMutableArray *) getAllGames; 
-(NSMutableArray *) getAllLiveGames; 
- (NSMutableDictionary *) getGameInfoObject: (NSString *) gameObjectID; 

-(void) postEventInfo: (NSDictionary *) eventInfoObject; 

@end 

GameInfo.h

-(void) fetchData{ 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setHTTPMethod:@"GET"]; 
    [request setURL:[NSURL URLWithString:url]]; 

    NSError *error = [[NSError alloc] init]; 
    NSHTTPURLResponse *responseCode = nil; 

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error]; 

    if([responseCode statusCode] != 200){ 
     NSLog(@"Error getting %@, HTTP status code %li", url, (long)[responseCode statusCode]); 
    } 

    jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 

} 

- (NSMutableDictionary *) getGameInfoObject: (NSString *) gameObjectID { 

[self fetchData]; 

DataParser *dataParserObject = [[DataParser alloc] init]; 

return [dataParserObject sendBackDetailObject:jsonDict andGameID:gameObjectID]; 
// and this is where i send this NSMutableDictionary to the problem described on the top 


} 
+0

的错误是明显的。你的'myDictionary'是一个'NSDictionary',而不是'NSMutableDictionary'。 – rmaddy 2014-10-19 21:14:11

+0

但即时通讯明确标记为NsMutableDictionary作为参数,我从哪里发送它是一个NsMutableDictionary。可以说这是一个NSDictionary我将如何解决它然后 – 2014-10-19 21:49:50

+0

变量类型是不相关的。实际的对象不是一个可变的字典。在你实际设置或获取'myDictionary'的地方显示代码。 – rmaddy 2014-10-19 21:50:53

回答

1

+[NSJSONSerialization JSONObjectWithData:options:error:]将默认返回NSDictionary不可改变的NSArray

你要么需要利用这个副本,并将其分配给您的实例变量

NSError *JSONError = nil; 

jsonDict = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError] mutableCopy]; 

if (!jsonDict) { 
    NSLog(@"Failed to parse JSON: %@", JSONError.localizedDescription); 
} 

或提供NSJSONReadingMutableContainers选项JSON解析方法

NSError *JSONError = nil; 

jsonDict = [NSJSONSerialization JSONObjectWithData:data 
              options:NSJSONReadingMutableContainers 
              error:&JSONError]; 

if (!jsonDict) { 
    NSLog(@"Failed to parse JSON: %@", JSONError.localizedDescription); 
} 
+0

辉煌,我用第二个选项谢谢! – 2014-10-19 23:14:13