gpt4 book ai didi

iOS - 文件输入 - 变量类型转换问题

转载 作者:行者123 更新时间:2023-11-29 04:11:50 26 4
gpt4 key购买 nike

使用我在 cimgf.com 上找到的以下代码将 JSON 文件输入到 Core Data 中:

NSString *filePathGPS = [[NSBundle mainBundle] pathForResource:@"gps_6kb" ofType:@"json"];


if (filePathGPS) {
NSString *contentOfFile = [NSString stringWithContentsOfFile:filePathGPS encoding:NSUTF8StringEncoding error:nil];
NSDictionary *jsonDict = [contentOfFile objectFromJSONString];

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *areaName = [NSEntityDescription
insertNewObjectForEntityForName:@"Area"
inManagedObjectContext:context];

NSDictionary *attributes = [[areaName entity] attributesByName];

for (NSString *attribute in attributes) {
for (NSDictionary * tempDict in jsonDict) {
NSLog(@"Attribute = %@", attribute);

id value = [tempDict objectForKey:attribute];

NSLog(@"Value = %@", value);

if (value == nil) {
continue;
}


[areaName setValue:value forKey:attribute];
}
}


NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}

我收到以下错误:

2013-01-12 12:11:09.548 SuperGatherData[1194:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "area2"; desired type = NSString; given type = NSNull; value = <null>.'

我明白为什么会发生错误,因为文件中的某些值是 null 而不是字符串。以下是 JSON 数据的示例:

   {
"area1": "International",
"area2": null,
"area3": null,
"area4": null,
"area5": null,
"latitude": "-25.2447",
"longtitude": "133.9453",
},
{
"area1": "Alaska",
"area2": "Anchorage & South Central Alaska ",
"area3": null,
"area4": null,
"area5": null,
"latitude": "61.2134",
"longtitude": "-149.8672",
},
{
"area1": "Alabama",
"area2": null,
"area3": null,
"area4": null,
"area5": null,
"latitude": "34.4112",
"longtitude": "-85.5737",
},

并意识到我需要在以下行中对属性进行类型转换:

for (NSString *attribute in attributes) {

我只是不知道修复是什么。我是 Objective-C 的新手,以前没有接触过强类型语言。

最佳答案

if (value == nil) 应该是 if ([value isEqual:[NSNull null]]) - 大多数 JSON 解析器表示显式 null 值由 NSNull 表示,因为无法将 nil 存储在 NSDictionaryNSArray 中.

关于iOS - 文件输入 - 变量类型转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297603/

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