iOS-文件输入-变量类型转换问题
使用我在cimgf.com上找到的以下代码将JSON文件输入核心数据: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
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) {