我有一個應用程序,它有一個UITabelView
從服務器端獲取其內容。在我的應用程序中,我每隔30秒從服務器讀取內容....我使用NSTimer
。 當我加載包含UITableView
的視圖時,此NSTimer
被初始化,當我離開此視圖時,該視圖無效。UITabelView沒有得到從服務器端的新內容更新
我的問題是這樣的:
如果在服務器端爲UITableView
的內容與新產品的更新,並在iPhone應用程序,以對服務器的請求的響應收到的JSON
包含項目..屏幕上出現的UITableView
仍未更新。
這是我如何做的:
//這一觀點被加載時啓動定時器和方法repeatServerRequest
被稱爲
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
if(playlistTimer == nil)
playlistTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target: self selector: @selector(repeatServerRequest) userInfo: nil repeats: YES];
}
//方法repeatServerRequest開始在一個新的線程後臺請求/ /服務器下載內容
- (void) repeatServerRequest{
[NSThread detachNewThreadSelector:@selector(backgroundThinking) toTarget:self withObject:nil];
}
- (void) backgroundThinking{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:@"a link to server"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request startAsynchronous];
[pool release];
}
///when the response from server comes in these methods are called:
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self performSelectorOnMainThread:@selector(didFindAnswer:) withObject:request waitUntilDone:YES];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(@"the value of error %@", error);
}
- (void) didFindAnswer:(ASIHTTPRequest *) request{
NSLog(@"update tabel");
SBJSON *parser = [[SBJSON alloc] init];
NSString *responseString = [request responseString];
NSArray *statuses = [parser objectWithString:responseString error:nil];
streams = [statuses valueForKey:@"_playLists"];
[parser release];
playList = [[NSMutableArray alloc] init];
idList = [[NSMutableArray alloc] init];
int ndx;
for (ndx = 0; ndx<streams.count; ndx++) {
NSDictionary *stream = (NSDictionary *)[streams objectAtIndex:ndx];
[playList addObject:[stream valueForKey:@"name"]];
[idList addObject:[stream valueForKey:@"id_playlist"]];
}
NSLog(@"playList %@", playList);
oneview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
tableViewPlaylist =[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
tableViewPlaylist.bounces=NO;
tableViewPlaylist.backgroundColor=[UIColor clearColor];
[tableViewPlaylist setDelegate:self];
[tableViewPlaylist setDataSource:self];
}
因此,當我更新服務器端的內容時,JSON th等我得到作爲響應在服務器端更新,但UITAbelView不是,UNLESS I RUN AGAIN MY APP
。任何想法爲什麼?
此外,您不需要在線程 –
上執行'ASIHTTPRequest'以添加到@ ThomasJoulin的評論[請求startAsynchronous]; 異步執行請求,並將在其啓動的線程上調用回調,因此不需要創建後臺線程。如果您使用[request startSynchronous],則需要創建後臺線程; (但是你會失去異步請求提供的很多靈活性)。 – jbat100