UIPickerview不显示来自JSON数组的数据

时间:2011-09-18 15:48:25

标签: json nsmutablearray nsarray uipickerview

我有一个UIPicker视图,我需要从JSON提要中加载数据。 我能够将数组数据写入NSLOG并显示它,但无法在UIPickerview中看到它。请参阅下面的代码并帮助我

另请告诉我如何在单击UI按钮时显示UIPicker视图,并在选择值时关闭UIPickerview。

#import "orderSamples.h"
#import "SBJson.h"
#import "JSON.h"

@implementation orderSamples

NSMutableArray *products;
NSArray *list;
NSMutableData *responseData;
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}
 */

- (void)viewDidLoad
{


    [super viewDidLoad];

    products = [[NSMutableArray alloc] init];

    responseData = [[NSMutableData data] retain];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http JSON URL"]];
    [[NSURLConnection alloc] initWithRequest:request delegate:self ];


}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    NSLog(@"didReceiveResponse"); 
    [responseData setLength:0]; 
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data]; 
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Connection failed: %@", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];


list = [[NSMutableArray alloc] init];


NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//[responseData release];

NSDictionary *dictionary = [responseString JSONValue];
NSArray *response = [[dictionary valueForKey:@"products"] retain];

list = [response valueForKey:@"product_name"];

NSLog(@"Here is the products list: %@",[response valueForKey:@"product_name"]);

self.pickerData = list;
[list release];    
}

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

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [list count];

}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [list objectAtIndex:row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    NSString *str = [list objectAtIndex:row];
    NSLog(@"Selected : %@" , str);
}

1 个答案:

答案 0 :(得分:0)

我认为问题在于这行代码:

list = [dictionary valueForKey:@"products"];

这是将一个对象分配给“list”变量,但该对象将被自动释放。而是尝试:

list = [[dictionary valueForKey:@"products"] retain];

你可能应该使用实例变量而不是全局变量,尽管如果你一次只有一个网络连接它并不重要。