noobie表刷新问题

时间:2011-04-06 22:21:18

标签: ios

我正在尝试学习IOS开发,我从一个示例RSS提要应用程序创建了一个项目,该应用程序从我的服务器上的XML提要文件加载数据。这工作正常,但如果按下主页按钮,我希望它刷新(ios多任务处理)。我已经尝试过[table reloaddata]并把它放在所有的viewdidload / viewdiddisappear部分中,但是它没有工作,并且它没有停在我已经放在它们上面的断点上。

@implementation RootViewController

- (void)viewDidLoad {
    // Add the following line if you want the list to be editable
    // self.navigationItem.leftBarButtonItem = self.editButtonItem;
    //[newsTable reloaddata];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
    }

    // Set up the cell
    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    [cell setText:[[stories objectAtIndex: storyIndex] objectForKey: @"title"]];

    return cell;
}

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     // Navigation logic

     int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];

     NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];

     // clean up the link - get rid of spaces, returns, and tabs...
     storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];
     storyLink = [storyLink stringByReplacingOccurrencesOfString:@"\n" withString:@""];
     storyLink = [storyLink stringByReplacingOccurrencesOfString:@" " withString:@""];

     NSLog(@"link: %@", storyLink);
     // open in Safari
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [newsTable reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([stories count] == 0) {
        [newsTable reloadData];
        NSString * path = @"http://www.myserver.co.uk/test.xml";
        [self parseXMLFileAtURL:path];
        //[NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(reloadData) userInfo:nil repeats:FALSE];
    }

    cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}

-(void)viewWillDisappear:(BOOL)animated {
    [newsTable reloadData];
}

- (void)viewDidDisappear:(BOOL)animated {
    [newsTable reloadData];}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    [newsTable reloadData];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
    [newsTable reloadData];
}

- (void)parserDidStartDocument:(NSXMLParser *)parser{   
    NSLog(@"found file and started parsing");
}

- (void)parseXMLFileAtURL:(NSString *)URL
{   
    stories = [[NSMutableArray alloc] init];

    //you must then convert the path to a proper NSURL or it won't work
    NSURL *xmlURL = [NSURL URLWithString:URL];

    // here, for some reason you have to use NSClassFromString when trying to alloc NSXMLParser, otherwise you will get an object not found error
    // this may be necessary only for the toolchain
    rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];

    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [rssParser setDelegate:self];

    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];

    [rssParser parse];
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);

    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{            
    //NSLog(@"found this element: %@", elementName);
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"item"]) {
        // clear out our story item caches...
        item = [[NSMutableDictionary alloc] init];
        currentTitle = [[NSMutableString alloc] init];
        currentDate = [[NSMutableString alloc] init];
        currentSummary = [[NSMutableString alloc] init];
        currentLink = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
    //NSLog(@"ended element: %@", elementName);
    if ([elementName isEqualToString:@"item"]) {
        // save values to an item, then store that item into the array...
        [item setObject:currentTitle forKey:@"title"];
        [item setObject:currentLink forKey:@"link"];
        [item setObject:currentSummary forKey:@"summary"];
        [item setObject:currentDate forKey:@"date"];

        [stories addObject:[item copy]];
        NSLog(@"adding story: %@", currentTitle);
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    //NSLog(@"found characters: %@", string);
    // save the characters for the current item...
    if ([currentElement isEqualToString:@"title"]) {
        [currentTitle appendString:string];
    } else if ([currentElement isEqualToString:@"link"]) {
        [currentLink appendString:string];
    } else if ([currentElement isEqualToString:@"description"]) {
        [currentSummary appendString:string];
    } else if ([currentElement isEqualToString:@"pubDate"]) {
        [currentDate appendString:string];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];

    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [newsTable reloadData];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

- (void)dealloc {

    [currentElement release];
    [rssParser release];
    [stories release];
    [item release];
    [currentTitle release];
    [currentDate release];
    [currentSummary release];
    [currentLink release];

    [super dealloc];
}

@end

3 个答案:

答案 0 :(得分:3)

我喜欢使用通知来处理这种情况。将此行代码添加到“viewDidLoad”方法

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateRSSFeed)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];

'updateRSSFeed'方法将执行类似这样的操作

- (void) updateRSSFeed
{
    NSLog( @"Feed Me!!!");
    // Code to restart loading the data from the RSS feed and ultimately reloading
    //  the table view.
}

并且不要忘记删除观察者,因此将其添加到'dealloc'方法

[[NSNotificationCenter defaultCenter] removeObserver: self];

在具有多个视图控制器的复杂应用程序中,可以在不退出应用程序的情况下取消分配视图控制器,并且可能会向不存在的实例发送通知,从而导致崩溃。

通知非常有用,因此请深入了解文档和其他来源,以了解如何使用它们。

最后,方法'applicationDidBecomeActive:'和'applicationWillEnterForeground:'将永远不会在根视图控制器中调用,因为它们是appDelegate遵守的应用程序委托协议的一部分。

答案 1 :(得分:0)

嘿,如果你想对应用程序进入后台做出反应,你应该实现

- (void)applicationDidEnterBackground:(UIApplication *)application
在你的appDelegate上

,并从那里触发数据重新加载。当应用程序进入后台时(即,当您“最小化”它,按主页按钮或切换到其他应用程序时,不会调用viewWillAppear。

干杯

答案 2 :(得分:0)

我不清楚你打电话给[tableView reloadData]的地方。根据您的描述,您必须在applicationWiilResignActive:期间调用它,但除非您已向操作系统指明要在后台下载,否则很可能无法运行。

但是我相信在调用此方法之前你必须有已经开始下载,这将解释为什么你看不到表重新加载或断点被调用。

我可能误解了你是如何进行通话的,但我认为你有一个基本的设计问题,因为你无法启动在停用时重新加载。