2013-10-15 2 views
-1

И в настоящее время я работаю над JSON. Я просто использую jsp webserver. И используя данные JSON, которые я хочу отобразить в моем uitableviewcell. Я пробовал какую-то программу. Но у меня есть некоторые ошибки.Как отобразить данные Json в UITableviewCell

Это мой JSON.

[{"result":[{"request_id":508,"ticket_number":"PA_1000508","email":"harI","user_id":6,"description":"Feed","createdTime":"10/15/2013 10:52:32 AM","status":"initiated"},{"request_id":507,"ticket_number":"PA_1000507","email":"hari","user_id":6,"description":"","createdTime":"10/15/2013 10:52:16 AM","status":"initiated"},{"request_id":505,"ticket_number":"PA_1000505","email":"hari","user_id":6,"description":"test","createdTime":"10/15/2013 10:42:26 AM","status":"initiated"},{"request_id":504,"ticket_number":"PA_1000504","email":"hari","user_id":6,"description":"desccccccccccccccccccc","createdTime":"10/15/2013 10:42:06 AM","status":"initiated"},

Я хочу, чтобы отобразить данные в моем uitableviewcell

Вот мой пример кода.

TotalRequest.h 

@interface TotalRequests : UIViewController<UITableViewDataSource,UITableViewDelegate> 
{ 
    NSMutableData *data; 
    NSArray *listItems; 
    NSURLConnection *connection; 
    NSString *stat; 
    IBOutlet UITableView *tableview; 
} 

TotalRequest.m 

- (void)viewDidLoad 
{ 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view from its nib. 
    [email protected]"Total Requests"; 
    NSURL *url=[NSURL URLWithString:@"http:sampleurl"]; 
    NSURLRequest *request=[NSURLRequest requestWithURL:url]; 
    connection=[[NSURLConnection alloc]initWithRequest:request delegate:self]; 
    if(connection)  
    { 
     data=[[NSMutableData alloc]init]; 
    } 
    data=[[NSMutableData alloc]init]; 
    [self performSelectorOnMainThread:@selector(fetchData) 
    withObject:data waitUntilDone:YES]; 
} 

-(void)fetchData:(NSData *)responseData 
{ 
    NSError *error=nil; 
    NSDictionary *json=[NSJSONSerialization JSONObjectWithData:responseData 
    options:kNilOptions error:&error]; 
    NSDictionary *tRequest=[json objectForKey:@"userId"]; 
    NSLog(@"Total Requests :%@",tRequest); 
    if(!tRequest) 
    { 
     NSLog(@"Error In Json :%@",error); 
    } 
    else 
    for(NSDictionary *newValue in tRequest) 
    { 
     NSString *tNumber=[newValue objectForKey:@"ticket_number"]; 
     NSString *time=[newValue objectForKey:@"createdTime"]; 
     stat=[newValue objectForKey:@"status"]; 
     NSLog(@"ticket_number :%@",tNumber); 
     NSLog(@"createdTime :%@",time); 
     NSLog(@"status :%@",stat); 
    } 
} 


- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
    } 
    cell.textLabel.text=[[listItems objectAtIndex:indexPath.row]objectForKey:@"ticket_number"]; 
    cell.textLabel.text=[[listItems objectAtIndex:indexPath.row]objectForKey:@"createdTime"]; 
    cell.textLabel.text=[[listItems objectAtIndex:indexPath.row]objectForKey:@"status"]; 
    return cell; 
} 


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


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

-(void)connection :(NSURLConnection *)connection didFailWithError:(NSError *)error 

{ 
    NSLog(@"Error in Connection"); 
} 

Сообщение об ошибке:

-[TotalRequests fetchData]: unrecognized selector sent to instance 0x7162820 15:02:36.685 sampleWebservices[2897:11303]Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TotalRequests fetchData]: unrecognized selector sent to instance 0x7162820' *** First throw call stack: (0x1c99012 0x10d6e7e 0x1d244bd 0x1c88bbc 0x1c8894e 0xb15fb4 0xb15e67 0x3d45 0xfc1c7 0xfc232 0xfc4da 0x1138e5 0x1139cb 0x113c76 0x113d71 0x11489b 0x114e93 0x114a88 0x3607 0xca285 0xca4ed 0xad45b3 0x1c58376 0x1c57e06 0x1c3fa82 0x1c3ef44 0x1c3ee1b 0x1bf37e3 0x1bf3668 0x1affc 0x28bd 0x27e5) 
+2

В чем проблема? – user1673099

+0

проверить мой ответ, часть цели-c: http://stackoverflow.com/questions/19108976/ios-objective-c-how-do-i-query-a-web-server-database-from-an- iphone-app/19110548 # 19110548 – Ilario

+0

Используйте отладчик, чтобы найти место ошибок при необходимости. И каковы эти ошибки? –

ответ

3

В TotalRequest.m Заменить код:

[self performSelectorOnMainThread:@selector(fetchData) withObject:data waitUntilDone:YES]; 

с этим:

[self performSelectorOnMainThread:@selector(fetchData:) withObject:data waitUntilDone:YES]; 

Пожалуйста, обратите внимание, что я добавил ":" для селектора (fetchData)

Когда вы используете методы performSelector и ваш метод получает параметр, вы должны добавить «:» к имени метода.

EDIT

После установления вашей первой проблемы, то теперь появляется второй. В объявлении интерфейса вы указываете, что вы реализуете UITableViewDataSource. Если вы проверить документацию яблока (https://developer.apple.com/library/ios/documentation/uikit/reference/UITableViewDataSource_Protocol/Reference/Reference.html), вы увидите, есть два обязательных метода: - Tableview: cellForRowAtIndexPath: требуется метод - Tableview: numberOfRowsInSection: требуется метод

Вы реализовали первый, но не второй. Это метод, который сообщает tableView, сколько строк будет в разделе. Я вижу, ваша модель данных «ListItems», так что вы должны добавить этот код в файл TotalRequest.m:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [listItems count]; 
} 

Я рассматриваю вас есть только один раздел. Пожалуйста, отрегулируйте логику этого метода, если у вас разные потребности.

+0

sampleWebservices [3169: 11303] Ошибка в Json: Error Domain = NSCocoaErrorDomain Code = 3840 «Операция не может быть выполнена. (Ошибка какао 3840.)» (Нет значение.) UserInfo = 0x901d000 {NSDebugDescription = Нет значения.} 2013-10-15 15: 49: 20.252 sampleWebservices [3169: 11303] - [TotalRequests tableView: numberOfRowsInSection:]: непризнанный селектор, отправленный в экземпляр 0x7569c10 2013-10- 15 15:49:20.274 sampleWebservices [3169: 11303] *** Завершение приложения из-за неперехваченного исключения «NSInvalidArgumentException», причина: '- [TotalRequests tableView: numberOfRowsInSection:]: непризнанный селектор, отправленный экземпляру 0x7569c10 –

+0

, все еще у меня получилась ошибка выше, если я нажму кнопку Totalrequestcell –

+0

@murthysurya Пожалуйста, обратите внимание, что теперь ошибка отличается. В нем говорится, что вы отправляете сообщение tableView: numberOfRowsInSection: вашему объекту TotalRequests. Я редактирую свой ответ, чтобы помочь вам. –

Смежные вопросы