2014-10-19 82 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