【问题标题】:How to write data in chunks into disk in ios如何在ios中将数据以块的形式写入磁盘
【发布时间】:2015-01-19 13:22:10
【问题描述】:

您好,在我的应用程序中,我正在下载一个 pdf 文件,并且我得到的总大小是大块的。现在,在我以块的形式获取这些数据后,我将其存储在 NSData 对象中,而剩余的块则附加到同一个对象中。在执行此应用程序时,由于内存不足警告而崩溃。有没有办法将数据写入磁盘,然后将数据附加到沙箱中的写入文件。有时文件超过 400 Mb。请帮助我。

【问题讨论】:

    标签: ios objective-c nsfilemanager nsfilehandle


    【解决方案1】:

    NSFileHandle 可用于此:

    类似这样的:

    Step1:创建一个名为_outputFileHandle的iVar;

    NSFileHandle *_outputFileHandle;
    

    Step2:调用prepareDataHandle一次:

    第 3 步:每当有数据垃圾进入时,调用writingDataToFile

    相应地修改您的工作流程,以便知道文件下载何时完成。

    -(void)prepareDataHandle
    {
        NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *outputFilePath = [documentsDirectory stringByAppendingPathComponent:@"anoutputfile.xxx"];
         if ([[NSFileManager defaultManager] fileExistsAtPath:outputFilePath] == NO)
        {
            NSLog(@"Create the new file at outputFilePath: %@", outputFilePath);
            BOOL suc = [[NSFileManager defaultManager] createFileAtPath:outputFilePath
                                                  contents:nil
                                                attributes:nil];
            NSLog(@"Create file successful?: %u", suc);
        }
        _outputFileHandle = [NSFileHandle fileHandleForWritingAtPath:outputFilePath];
    }
    
    -(void)writingDataToFile:(NSData *)dataToWrite
    {
        if (dataToWrite.length != 0)
        {
            [_outputFileHandle writeData:dataToWrite];
        }
        else   //you can use dataToWrite with length of 0 to indicate the end of downloading or come up with some unique sequence yourself
        {
            NSLog(@"Finished writing... close file");
            [_outputFileHandle closeFile];
        }
    }
    

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 2017-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      相关资源
      最近更新 更多