Pergunta

I have a app which has a download manager built into it. When a file is downloaded, it gets saved to a folder inside of the documents folder. Now I have implemented a time and date stamp in my table view cell. However, When switching from one view controller back to my table view, the time and date updates to the current time.

Below is my code I'm working with, and as always any help would be appreciated.

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

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; } //did the subtitle style

    NSUInteger row = [indexPath row];
    cell.textLabel.text = [directoryContents objectAtIndex:row];


    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"EEE, MMM/d/yyyy, hh:mm aaa"];
    NSDate *date = nil;

    if (indexPath.row == 0)
    {
        date = [NSDate date];
        NSString *dateString = [dateFormatter stringFromDate:date];
        cell.detailTextLabel.text = dateString;
    }

    return cell;
}
Foi útil?

Solução 2

Decided to circle back to this. I ended up getting it figured out (not that I was working on it this whole time lol).

Anyways heres what I did:

//Setting the date
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"my folder"];
    filePath = [filePath stringByAppendingPathComponent:fileName];

    NSDate *creationDate = nil;
    NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:nil];
    creationDate = attributes[NSFileCreationDate];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yyyy"];
    NSString *dateString = [dateFormatter stringFromDate:creationDate];

    cell.detailTextLabel.text = dateString;

Hope it helps somebody.

Outras dicas

tableView:cellForRowAtIndexPath: will be called every time the table is reloaded, and hence the time will be updated to the current time because [NSDate date] will be called again.

Instead of calculating the date in tableView:cellForRowAtIndexPath: you should store it elsewhere (such as in an class level NSMutableArray) and set it when the file finishes downloading. This way it won't be reset each time the table loads.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top