首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >分块读取NSData

分块读取NSData
EN

Stack Overflow用户
提问于 2015-07-01 20:22:29
回答 1查看 144关注 0票数 1

我正在用ios8实现扩展。在这个import函数中,返回一个url。我需要从其中读取数据并保存到我的应用程序中。

下面是代码。

代码语言:javascript
复制
NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
    NSError *error;
    __block NSData *data;
    [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        data = [NSData dataWithContentsOfURL:newURL];
//saving in document directory
    }];

我的问题是,如果文件太大,dataWithContentsOfURL会因为内存不足而导致崩溃。

我想要一种方法,可以从url中读取数据,保存在我的文档中,然后读取下一部分并继续追加。因此,它不会有内存问题。

有人能帮帮忙吗。

EN

回答 1

Stack Overflow用户

发布于 2015-07-03 13:54:19

找到了两个解决方案。1-使用的NSURLConnection。使用NSFileHandle在文件中写入数据。

代码语言:javascript
复制
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1{
//    [data appendData:data1];
    [self.currentFileHandle seekToEndOfFile];
    [self.currentFileHandle writeData:data1];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self.currentFileHandle closeFile];
    self.currentFileHandle = nil;
}

  1. ,而不是将其转换为数据然后保存。使用以下命令复制文件。

nil协调器* fileCoordinator = [NSFileCoordinator alloc :nil];

[newURL协调读取项目属性:url options:NSFileCoordinatorReadingWithoutChanges错误:nil byAccessor:^(NSURL *fileCoordinator) {

NSFileManager * fileManager = [NSFileManager分配初始化];

代码语言:javascript
复制
NSError * error;

NSArray *paths = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];


NSURL *urlDestination = [paths lastObject];
                    urlDestination = [urlDestination URLByAppendingPathComponent:[url lastPathComponent]];


if([[NSFileManager defaultManager] fileExistsAtPath:[urlDestination relativePath]]){


[[NSFileManager defaultManager] removeItemAtPath:[urlDestination relativePath] error:nil];

}

BOOL success = fileManager copyItemAtURL:url浏览:url目标错误:&error;if (成功){} }];

我使用了第二个解决方案。抱歉,对齐错误。我试了很多,但还是不能很好地来。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31161185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档