下载大文件时应用程序崩溃 – NSFileHandle seekToEndOfFile

我有一个循环,获取一堆文件的URL(10个小的txt文件和700KB左右的大图像文件),并运行“getFile”为每个文件创build一个NSUrlConnection。

当应用程序在[file writeData:data]之前到达[file seekToEndOfFile]时,它将崩溃:

*** Terminating app due to uncaught exception 'NSFileHandleOperationException', reason: '*** -[NSConcreteFileHandle seekToEndOfFile]: No such process' *** First throw call stack: 

奇怪的是,如果我通过代码(即慢慢允许每个连接去回来),然后所有文件下载罚款。 如果我只是让应用程序做它的事情崩溃。

这里是连接的代码:

 -(void)getFile { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]]; NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; [conn start]; } - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { NSString *fileName = [[response URL] lastPathComponent]; NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]stringByAppendingPathComponent:fileName]; [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; file = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; [file seekToEndOfFile]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [file seekToEndOfFile]; // crashing here [file writeData:data]; } - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse*)cachedResponse { return nil; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"Connection is %@", connection); [file closeFile]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"error - %@", error); } 

我的应用程序在保持对传出连接的引用时有问题吗? 我假定NSURLConnections,默认情况下,是asynchronous的,你不需要“跟踪”他们?

编辑我已经subclassed NSURLConnection和实例化如下:

 -(void)getFile { NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:fullURL]]; FileURLConnection *conn = [[FileURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES ]; conn.fileName = [fullURL lastPathComponent]; [conn start]; } 

我想你是一个代表同时下载几个文件。 尝试子类NSURLConnection连接,并添加它的保护file ,而不是委托的文件属性。 我认为你不需要[file seekToEndOfFile];

编辑:示例subclassed NSURLConnection

 @interface FileURLConnection: NSURLConnection @property (nonatomic, strong) NSFileHandle *file; @end