[英]Reload TableView Data from DB
在我的應用程序中,我通過php中的php文件從git dat從Internet上獲取數據,並在表視圖中顯示數據,但是我需要每分鍾重新加載數據,我可以每分鍾獲取新數據,但是我不能在表視圖中替換它。
1)你知道怎么做嗎?
2)如果您知道如何使我的代碼更簡單,並刪除不需要的代碼? 我會感謝你的。
我的ViewController.m
#import "ViewController.h"
#import "CJSONDeserializer.h"
@implementation ViewController
@synthesize tblMain, rows;
NSURL *url;
NSString *jsonreturn;
NSData *jsonData;
NSError *error;
NSDictionary *dict;
UITableViewCell *cell;
static NSString *CellIdentifier;
- (void)viewDidLoad{
[super viewDidLoad];
[self GetData];
}
-(void)GetData{
url = [NSURL URLWithString:@"http://ar2.co/savola/"];
jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn);
jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
dict = [[[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] retain];
rows = [dict objectForKey:@"savola"];
NSLog(@"Array: %@",rows);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
dict = [rows objectAtIndex: indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@ - %@", [dict objectForKey:@"company"], [dict objectForKey:@"price"]];
cell.detailTextLabel.text = [dict objectForKey:@"time"];
return cell;
}
@end
要強制表重新加載其信息,請從視圖控制器類中調用[self.tableView reloadData]
。 這將再次調用所有數據源方法,並且還將更新顯示。
從服務器獲取新數據后,應重新加載表。 就像在您的GetData方法中一樣:
- (void)GetData
{
url = [NSURL URLWithString:@"http://ar2.co/savola/"];
jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn);
jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
dict = [[[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] retain];
rows = [dict objectForKey:@"savola"];
NSLog(@"Array: %@",rows);
[yourTable reloadData];
}
您需要使用reloadData
方法重新加載表視圖以顯示新數據。
但是正如您提到的那樣-“但是我需要每分鍾重新加載我的數據”
因此,為此您可以將接收到的數據與現有數據進行檢查,如果新數據中發生了更改,則僅重新加載表,否則跳過該表。
如果您每隔一分鍾不必要地重新加載表而不更改數據,那將是不正確的,而且還會減慢您的應用程序的速度。
在這種情況下,我建議您使用NSFetchedResultsController 。 僅在需要時,它將自動更新您的表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.