gpt4 book ai didi

objective-c - Plist 数组到 NSDictionary

转载 作者:太空狗 更新时间:2023-10-30 03:23:10 25 4
gpt4 key购买 nike

我有一个 plist:

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

我正在尝试将其加载到 NSDictionary 中:

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

我总是得到 50 的数组计数,但字典计数为零。所以我尝试遍历数组并将其添加到字典中:

NSDictionary *eachState;
for (eachState in thisArray) {
State *thisState = [[State alloc] initWithDictionary:eachState];
[myDic setObject:thisState forKey:thisState.name];
}

但是循环抛出异常:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '*** -[NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'

State 是一个属性与我的 plist 匹配的类。我究竟做错了什么?我在这里看到各种相关问题,但我无法理解。

最佳答案

两个问题:

  • 将 plist 加载到 NSDictionary 中:

这是一个简单的问题,看来你已经想通了。 plist 中的全局对象是一个数组,而不是一个字典,所以当你将它加载到字典中时,它不知道该做什么(不兼容的类型),所以你得到一个空字典。

  • 遍历字典数组:

从您得到的异常中,您在字典上调用“setObject:forKey:”,它被初始化为 NSDictionary,而不是 NSMutableDictionary。该指针的类型为 NSMutableDictionary,但不是实际的内存对象。你需要改变你的线路。

NSMutableDictionary *myDic = [[NSDictionary alloc] initWithContentsOfFile:path];

NSMutableDictionary *myDic = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

实际上,由于从文件中加载字典会为您提供一个空字典,因此您在尝试从文件中加载它是在浪费周期,应该只创建一个新字典:

NSMutableDictionary *myDic = [[NSMutableDictionary alloc] init];

关于objective-c - Plist 数组到 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1343121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com