我试图将数据从我的JSON文件传递到一个简单的ViewController上,但我不知道将数据真正传递到哪里。我只能添加到我的setDataToJson
方法中,还是应该将数据添加到我的viewDidLoad
方法中?
以下是我的代码
@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
}
发布于 2012-06-03 16:40:46
问题在于您尝试检索文件的方式。为了正确地完成它,你应该首先在包中找到它的路径。尝试如下所示:
+(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];
}
发布于 2012-06-03 13:02:28
它应该是valueForKey
。
示例:
name.text = [infomation valueForKey:@"AnimalName"];
https://stackoverflow.com/questions/10866403
复制相似问题