Tôi có một plist:Plist Array NSDictionary
<plist version="1.0">
<array>
<dict>
<key>name</key>
<string>Alabama</string>
<key>abreviation</key>
<string>AL</string>
<key>date</key>
<string>1819</string>
<key>population</key>
<string>4,627,851</string>
<key>capital</key>
<string>Montgomery</string>
<key>largestCity</key>
<string>Birmingham</string>
</dict>
<dict>
<key>name</key>
<string>Alaska</string>
<key>abreviation</key>
<string>AK</string>
<key>date</key>
<string>1959</string>
<key>population</key>
<string>683,478</string>
<key>capital</key>
<string>Juneau</string>
<key>largestCity</key>
<string>Anchorage</string>
</dict>
...
</array>
</plist>
Tôi cố gắng để tải nó thành một NSDictionary như thế này:
NSString *path = [[NSBundle mainBundle] pathForResource:@"stateInfo" ofType:@"plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path]) {
NSLog(@"The file exists");
} else {
NSLog(@"The file does not exist");
}
NSMutableDictionary *myDic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
//NSDictionary *myDic = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"The count: %i", [myDic count]);
NSArray *thisArray = [[NSArray alloc] initWithContentsOfFile:path];
NSLog(@"The array count: %i", [thisArray count]);
tôi luôn luôn nhận được một số mảng của 50 nhưng một số từ điển bằng không. Vì vậy, tôi đã cố gắng lặp qua mảng và thêm nó vào từ điển:
NSDictionary *eachState;
for (eachState in thisArray) {
State *thisState = [[State alloc] initWithDictionary:eachState];
[myDic setObject:thisState forKey:thisState.name];
}
Nhưng vòng lặp là ném một ngoại lệ:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
Nhà nước là một lớp học với tính chất phù hợp với tôi plist. Tôi đang làm gì sai? Tôi thấy tất cả các loại câu hỏi liên quan ở đây nhưng tôi không thể có được nó.
tôi đã nhận nó. Tôi đã có một không phù hợp và NsMutableDictionary được phân bổ như là một NSDictionary. – Bryan
Và dĩ nhiên, tôi đã bỏ lỡ nhận xét này cho đến sau khi tôi đăng câu trả lời của mình. – bobDevil