1

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

4

2 回答 2

2

NSFileHandle可用于此:

像这样的东西:

Step1:创建一个名为_outputFileHandle;

NSFileHandle *_outputFileHandle;

Step2:调用prepareDataHandle一次:

Step3: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];
    }
}
于 2015-01-19T18:18:57.310 回答
0

你可以使用一个NSOutputStream

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Streams/Articles/WritingOutputStreams.html

于 2015-01-19T14:10:23.960 回答