Как проверить размер файла документа текущей строки UITableView - PullRequest
1 голос
/ 28 января 2012

В настоящее время у меня есть UITableView, показывающий каталог документов моего приложения. Как я могу получить размер файла документа текущей строки?

Мой код в настоящее время выглядит следующим образом:

- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    // layout the cell
    cell.textLabel.text = [self.drive.filesArray objectAtIndex:indexPath.row];
    NSInteger iconCount = [docInteractionController.icons count];
    cell.imageView.image = [docInteractionController.icons objectAtIndex:iconCount - 1];

    NSString *fileURLString = [self.drive.filesArray objectAtIndex:indexPath.row];
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileURLString error:nil];
    NSString *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
    long long fileSize = [fileSizeNumber longLongValue];

    cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@",
                                 fileSizeNumber, [self.drive.filesArray objectAtIndex:indexPath.row]];

    return cell;
}

К сожалению, это не работает. Есть идеи?

Ответы [ 2 ]

1 голос
/ 29 января 2012

Я не знаю, что такое self.drive.filesArray, но если вы сделаете это с NSDocumentDirectory, получите путь, а затем файлы по этому пути, он будет работать.

Вот пример, который работает для меня, и я думаю, что это способ работы с каталогом документов для приложения на iOS:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *files = [fm contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSString *fileFirst = [files objectAtIndex:0];
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, fileFirst];
NSDictionary *attrs = [fm attributesOfItemAtPath:fullPath error:nil];
long long fileSize = [attrs fileSize];

NSLog(@"File is %@ and size is %lld",fileFirst, fileSize)

В итоге вы получите нечто похожее на

2012-01-28 22:34:00.916 fileOperations[57498:f803] File is smallImage.jpg and size is 30979

Я думаю, у вас все еще неправильный путь, мой (на iPhone с iOS 5.0.1) -

/var/mobile/Applications/DA47CD6A-8AA8-4739-8CCB-6087F30C0954/Documents/smallImage.jpg

точка здесь Документы . Исправьте ваш код, чтобы получить правильный путь, сохраните файлы по правильному пути, и вы сможете получить атрибуты из файлов. Возможно, ваш файл не существует или у fm просто нет прав, чтобы получить то, что вы хотите. Я не знаю, потому что вы отправляете ошибки из файлового менеджера в объект nil . Также вопрос, как вы собираете массив self.drive.filesArray ? Попробуйте собрать свой self.drive.filesArray таким образом, как я писал выше. Это работает.

0 голосов
/ 28 января 2012

Вы должны исправить свой код:

NSLog(@"fileURLString %@", fileURLString);
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileURLString error:nil];
NSLog(@"fileAttributes %@", fileAttributes);
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
NSLog(@"fileSizeNumber %@", fileSizeNumber);

cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@", fileSizeNumber, [self.drive.filesArray objectAtIndex:indexPath.row]];

Проверьте, правильно ли вы указали fileURLString для получения атрибутов. Чтобы получить больше информации о структуре структуры каталогов приложения iOS, полезно ознакомиться с Руководство по программированию файловой системы

...