UITabelView没有得到从服务器端的新内容更新
问题描述:
我有一个应用程序,它有一个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
。任何想法为什么?
答
两个主要问题:
- 您在每次服务器更新创建一个新的UITableView。这是不必要的。
- 即使您想要一个新的tableView,也不会将其添加为主视图的子视图。
你应该做的就是不要创建新的tableView。在主线程上更新数据模型调用[tableView reloadData]
之后。你的桌子会更新,一切都很好。假设你已经正确配置了所有东西,而且听起来好像你在启动应用程序时看到了预期的数据。
此外,您不需要在线程 –
上执行'ASIHTTPRequest'以添加到@ ThomasJoulin的评论[请求startAsynchronous]; 异步执行请求,并将在其启动的线程上调用回调,因此不需要创建后台线程。如果您使用[request startSynchronous],则需要创建后台线程; (但是你会失去异步请求提供的很多灵活性)。 – jbat100