2012-08-13 49 views

回答

3

从服务器获取数据不同步,你可以使用NSURLConnectionNSURLConnectionDelegate方法

在接口文件:

@interface ViewController : UIViewController<NSURLConnectionDelegate, UITextFieldDelegate> { 
    NSMutableData *mutableData; 
} 
-(void)getDataUsingText:(NSString *)text; 
@end 

在实现文件:

@implementation ViewController 
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *value =[textField.text stringByReplacingCharactersInRange:range withString:string]; 
    [self getDataUsingText:value]; 
    return YES; 
} 


-(void)getDataUsingText:(NSString *)text; 
{ 
    NSString *urlString = [NSString stringWithFormat:@"http://...."]; 
    NSURL *url =[NSURL URLWithString:urlString]; 
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; 
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    [conn start]; 
} 


-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    mutableData = [[NSMutableData alloc] init]; 
} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [mutableData appendData:data]; 
} 


-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{  
    NSString *dataString = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding]; 
    NSLog(@"your data from server: %@", dataString); 
    // Here you got the data from server asynchronously. 
    // Here you can parse the string and reload the picker view using [picker reloadAllComponents]; 

} 
@end 

必须委托设为文本字段,您必须使用NSURLConnectionDelegate方法中的数据实现选取器。而this是加载选取器视图的教程。

+0

非常感谢.. :)我得到了你的解决方案...... :) – python 2012-08-14 03:35:39