Ios noobie表格刷新问题

Ios noobie表格刷新问题,ios,Ios,我试图学习IOS开发,我从一个示例RSS提要应用程序创建了一个项目,该应用程序从我服务器上的XML提要文件加载数据。这工作正常,但我希望它刷新,如果主页按钮按下(ios多任务)。我尝试过[table reloaddata]并将其放在所有viewdidload/ViewDidEnglishe部分中,但它不工作,也没有在我放在它们上面的断点上停止 @implementation RootViewController - (void)viewDidLoad { // Add the foll

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

@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

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

- (void)applicationDidEnterBackground:(UIApplication *)application
在appDelegate上,并从那里触发数据重新加载。当应用程序进入后台时(即当您“最小化”它、按home按钮或切换到其他应用程序时),不会调用ViewWillAppeal


干杯

我不太清楚您从何处调用
[tableView reloadData]
。根据您的描述,您必须在
应用程序wiilResignActive:
期间调用它,但除非您向操作系统指示要在后台下载,否则这很可能不会运行

但是,我认为在调用此方法之前,您必须已经开始下载,这将解释为什么您既看不到重新加载表,也看不到调用的断点


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

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

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(updateRSSFeed)
                                             name:UIApplicationWillEnterForegroundNotification
                                           object:nil];
“UpdatersFeed”方法将执行如下操作

- (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];
在具有多个视图控制器的复杂应用程序中,可以在不退出应用程序的情况下释放视图控制器,并且可能会向不存在的实例发送通知,从而导致崩溃

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

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