Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS-文件输入-变量类型转换问题_Ios_Xcode_Types - Fatal编程技术网

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

iOS-文件输入-变量类型转换问题,ios,xcode,types,Ios,Xcode,Types,使用我在cimgf.com上找到的以下代码将JSON文件输入核心数据: NSString *filePathGPS = [[NSBundle mainBundle] pathForResource:@"gps_6kb" ofType:@"json"]; if (filePathGPS) { NSString *contentOfFile = [NSString stringWithContentsOfFile:filePathGPS encoding:NSUTF8StringEnco

使用我在cimgf.com上找到的以下代码将JSON文件输入核心数据:

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>.'
并意识到我需要对以下行中的属性进行类型转换:

for (NSString *attribute in attributes) {

我只是不知道那是什么办法。我是Objective-C新手,以前从未处理过强类型语言。

if(value==nil)
应该是
if([value isEqual:[NSNull-null]])
-大多数JSON解析器通过
NSNull
表示显式的
null
值,由于不能在
NSDictionary
NSArray

中存储
nil
,因此这与类型转换无关,这只是为了愚弄编译器。请阅读Objective-C为什么是一种动态语言,理解后再回来。好吧,我现在意识到错误与行
[areaName setValue:value forKey:attribute]有关,并且上面跳过nil值的IF语句并没有像它应该跳过的那样跳过这些值。仍然不知道为什么。我怀疑
if(value==nil)
应该是
if([value isEqual:[NSNull null]])
。这很好地工作了。谢谢我正在交替编写/阅读文档,现在我将后退一步,阅读更多文档。我给出了一个答案,如果有帮助,请接受/投票,谢谢。
for (NSString *attribute in attributes) {