我知道有很多问题像我一样,但仍然无法让它发挥作用?
我有一个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 :(得分:1)
+[NSJSONSerialization JSONObjectWithData:options:error:]
将返回NSArray
NSDictionary
个不可变的内容。
您需要获取此副本并将其分配给您的实例变量
NSError *JSONError = nil;
jsonDict = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&JSONError] mutableCopy];
if (!jsonDict) {
NSLog(@"Failed to parse JSON: %@", JSONError.localizedDescription);
}
或者为JSON解析方法提供NSJSONReadingMutableContainers
选项
NSError *JSONError = nil;
jsonDict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&JSONError];
if (!jsonDict) {
NSLog(@"Failed to parse JSON: %@", JSONError.localizedDescription);
}