【发布时间】:2011-08-26 11:34:27
【问题描述】:
我有一个实现UITableViewDelegate 和NSXMLParserDelegate 的类。我的应用是基于标签的。当我选择正确的选项卡时,在我的类的 viewWillAppear 方法中,我启动我的 xml 解析器以解析特定 url 处的 rss 提要,然后我用提要的内容填充我的 UITableView。
现在我想要一个按钮来“刷新”视图(即再次解析 rss 提要并显示新结果)。所以,我有这个方法作为刷新按钮的动作:
-(IBAction)refreshFeeds:(id)sender
{
if (stories){
[stories release]; // Stories is an NSMutableArray for storing the parsed feeds
stories = nil;
}
[self viewWillAppear:YES];
NSLog(@"RELOADING!!!!!!!!!!!!!!!");
}
我的问题是,当我按下“刷新”按钮时,视图变为空白,好像没有要显示的提要一样。
如果然后我切换到另一个选项卡然后回来,表格视图将再次填充提要。
我究竟做错了什么?提前谢谢你。
(这是我如何实现类的一部分)
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
if ([stories count] == 0){
NSString * path = @"http://www.theRssUrl.com";
[self parseXMLFileAtURL:path];
}
}
//custom method to parse rss xml
- (void)parseXMLFileAtURL:(NSString *)URL {
if (stories) {
[stories release];
stories = nil;
}
stories = [[NSMutableArray alloc] init];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
//you must then convert the path to a proper NSURL or it won't work
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser parse];
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
[newsTable reloadData]; //newsTable is the UITableView i want to refresh
self.view = newsTable;
[rssParser release];
rssParser = nil;
}
编辑:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Configure the cell.
static NSString *MyIdentifier = @"MyIdentifier";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil){
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
int storyIndex = indexPath.row;
cell.lTitle.text = [[stories objectAtIndex: storyIndex] objectForKey: @"title"];
cell.lSummary.text = [[stories objectAtIndex: storyIndex] objectForKey: @"summary"];
return cell;
}
【问题讨论】:
-
不要在
- (void)viewWillAppear:(BOOL)animated中调用[super viewDidAppear:animated];调用[super viewWillAppear:animated];。 -
你好@Nick 谢谢你的回复。第一个只是我写问题时的类型错误,实际上是 [super viewWillAppear:animated];至于你的第二个 cmets,在 refreshFeeds 方法中,我清空了 stories 数组,所以计数应该是 0 - 我在这里遗漏了什么吗?
-
@CrisDeBlonde 您可以直接调用
[self parseXMLFileAtURL:path];来刷新您的提要,因为此方法会清空数组。不要直接调用 viewWillAppear。只需在 viewWillAppear 和 refreshFeeds 中调用 parseXMLFileAtURL。 -
@CrisDeBlonde 我很瘦,如果您在 viewController 中,这个
self.view = newsTable;是不正确的。您应该将您的 tableView 添加到 loadView 或使用 nib 文件到您的视图控制器,然后在 parserDidEndDocument 中调用[tableView reloadData]。 -
@Nick 我已经尝试调用
[self parseXMLFileAtURL:path];而不是viewWillAppear,结果是一样的。我不确定我是否理解您最后的评论,请您再解释一下吗?
标签: iphone objective-c uitableview reload