0

这个网站上有一个与此类似的问题,但由于我不能以问题的形式对该问题添加其他评论,所以我选择在这里写我的,请原谅我。这里,

我在本地服务器上有一个 JSON 文件,并试图访问我的 UIPickerView 上的值。问题是我得到一个“问号,即“?”“而不是 JSON 文件上的字符串。是什么问题,我该如何解决?我还是个初学者,所以放轻松。

这是代码,

#import "ViewController.h"
#import "JSON.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize picker;
@synthesize terrainJsonArray;

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *terrainString = [NSString stringWithFormat:@"http://terrainracing.com/ios/events_json.php"];

NSURL *terrainUrl = [NSURL URLWithString:terrainString];

NSData  *terrainData = [NSData  dataWithContentsOfURL:terrainUrl];

NSError *error;

self.terrainJsonArray = [NSJSONSerialization JSONObjectWithData:terrainData options:kNilOptions error:&error];

NSLog(@"%@", terrainJsonArray);

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
 numberOfRowsInComponent:(NSInteger)component {
return self.terrainJsonArray.count;
}

#pragma mark Picker Delegate Methods
- (UIView *)pickerView:(UIPickerView *)pickerView
         titleForRow:(NSInteger)row
{

return [self.terrainJsonArray objectAtIndex:row];

}
@end

在此处输入图像描述

4

1 回答 1

2

Start by fixing your delegate method - - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component returns NSString not UIView and you need to obviously return a string for it to work

I can see in your response items as

{"event_name":"Phoenix","date":"Oct 27","event_id":"14"}

so you need to grab the string of "sub-item" you want to display

for instance

return [[self.terrainJsonArray objectAtIndex:row] valueForKey:@"event_name"];
于 2012-12-18T12:28:22.680 回答