17

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
}
4

2 に答える 2

40

問題は、ファイルを取得しようとしている方法です。正しく行うには、最初にバンドル内のパスを見つける必要があります。次のようなことを試してください:

+(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-03T08:40:46.037 に答える
1

valueForKey代わりにすべきです。

例:

name.text = [infomation valueForKey:@"AnimalName"];
于 2012-06-03T05:02:28.357 に答える