Add one row to TableView each day app used

和自甴很熟 提交于 2019-12-12 09:49:26

问题


I am building an app that will be used as a daily reading guide. The data is all stored in an XML that will be stored in app, and sorted based off pubDate. On the number of rows in each section code, if I put in just a number, I get errors, but if I put in the

[array count];

it shows every single item. Could I get some suggestions for what to do to accomplish my goal?

EDIT: Here is more code to my app. I use ASIHTTPRequest and GDataXML to parse the XML and store each item in an array. What I am trying to do is show only earliest entry day 1, add the next day 2, and so forth. If I put in any other number in the numberOfRowsInSection besides the array count, it crashes. I believe this is due to the code used to sort the array entries by date.

- (void)requestFinished:(ASIHTTPRequest *)request {

    [_queue addOperationWithBlock:^{

        NSError *error;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData] 
                                                               options:0 error:&error];
        if (doc == nil) { 
            NSLog(@"Failed to parse %@", request.url);
        } else {

            NSMutableArray *entries = [NSMutableArray array];
            [self parseFeed:doc.rootElement entries:entries];                

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                for (RSSEntry *entry in entries) {

                    int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
                        RSSEntry *entry1 = (RSSEntry *) a;
                        RSSEntry *entry2 = (RSSEntry *) b;
                        return [entry1.articleDate compare:entry2.articleDate];
                    }];

                    [_allEntries insertObject:entry atIndex:insertIdx];
                    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationRight];

                }                            

            }];

        }        
    }];
    [self.refreshControl endRefreshing];

}

How can I change this to sort by date, show the earliest one on the first day, and add one each day?


回答1:


I would store a date value into your NSUserDefaults and use it to compare and see if the day has changed, then use that to modify the number of rows in the section. I have heavily commented this code, hoping it will better explain.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    int numberOfDays = 0;   //initialize integer variable    

    //get the current date from the user's device
    NSDate *now = [NSDate date];

    //create a dateformatter to handle string conversion
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    // String to store in defaults.
    NSString *todaysDateString = [dateFormatter stringFromDate:now];

    // get access to the user defaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if (![defaults valueForKey:@"date_last_opened"]) {

        // if there is no value for the key, save today's date as the string we formatted
        [defaults setValue:todaysDateString forKey:@"date_last_opened"];

    } else {

        // there is already a value for date-last-opened, so pull it from the defaults, and convert it from a string back into a date.
        NSDate *dateLastOpened = [dateFormatter dateFromString:[defaults valueForKey:@"date_last_opened"]];

        if ([dateLastOpened compare:now] == NSOrderedAscending) {

            // if the date_last_opened is before todays date, get the number of days difference.

            unsigned int unitFlags = NSDayCalendarUnit;
            NSDateComponents *comps = [calendar components:unitFlags fromDate:dateLastOpened  toDate:now options:0];

            numberOfDays = [defaults integerForKey:@"totalDays"] + [comps day];
        [defaults setInteger:numberOfDays forKey:@"totalDays"];
        }
    }

return numberOfDays;

}

EDIT: This code assumes, you've already set an NSUserDefault value for a key similar to @"totalDays" to 1 when the app first launches, like in viewDidLoad maybe:

if (![defaults integerForKey:@"totalDays"]) {

        // if there is no value for the key, set it to 1
        [defaults setInteger:1 forKey:@"totalDays"];

    }



回答2:


In your class AppDelegate.m you can do this :

//Application did launch
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  int count = [[NSUserDefaults standardUserDefaults] integerForKey:@"LaunchCount"];
  if(count < 0) count = 0;
  [[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"LaunchCount"];
}

//The application was in background and become active
- (void)applicationWillEnterForeground:(UIApplication *)application
{
  int count = [[NSUserDefaults standardUserDefaults] integerForKey:@"LaunchCount"];
  if(count < 0) count = 0;
  [[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"LaunchCount"];
}

Then using the NSUserDefault Key @"LaunchCount" you can add an Table-Row.




回答3:


Sounds like you want one section with [array count] rows, whereas right now you're returning [array count] sections AND [array count] rows.




回答4:


How about something like a NSTimeInterval of 24 hours.



来源:https://stackoverflow.com/questions/13713471/add-one-row-to-tableview-each-day-app-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!