我正在尝试将数据从 JSON 文件传递到简单的 ViewController 上,但我不知道在哪里实际传递该数据。我可以添加到我的setDataToJson
方法或者我会将数据添加到我的viewDidLoad
method?
这是我的代码
@interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation;
@end
@implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation{
NSData* data = [NSData dataWithContentsOfFile:fileLocation];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
@end
@implementation ViewController
@synthesize name;
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(void)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
name.text = [infomation objectForKey:@"AnimalName"];//does not pass data
}
问题在于您尝试检索文件的方式。为了正确执行此操作,您应该首先在包中找到它的路径。尝试这样的事情:
+(NSDictionary*)dictionaryWithContentsOfJSONString:(NSString*)fileLocation{
NSString *filePath = [[NSBundle mainBundle] pathForResource:[fileLocation stringByDeletingPathExtension] ofType:[fileLocation pathExtension]];
NSData* data = [NSData dataWithContentsOfFile:filePath];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions error:&error];
// Be careful here. You add this as a category to NSDictionary
// but you get an id back, which means that result
// might be an NSArray as well!
if (error != nil) return nil;
return result;
}
完成此操作并加载视图后,您应该能够通过检索 json 来设置标签,如下所示:
-(void)setDataToJson{
NSDictionary *infomation = [NSDictionary dictionaryWithContentsOfJSONString:@"Test.json"];
self.name.text = [infomation objectForKey:@"AnimalName"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setDataToJson];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)