避免内存爆增的方法

一、NSOutputStream

//创建流,append为YES的话,每次写入都是追加到文件尾部
 self.outpustream = [NSOutputStream outputStreamToFileAtPath:[self getSaveFilePath] append:YES];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       
        [self.outpustream open];
        [self.outpustream write:data.bytes maxLength:data.length];
        [self.outpustream close];
        
//        [self saveFile:data];
    });

二、NSFileHandle

- (void)saveFile:(NSData *)data {
    //保存文件的路径
    NSString *filePath = [self getSaveFilePath];
    //如果文件不存在,返回的是nil
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    //判断文件存不存在
    if (fileHandle == nil) {
        //如果文件不存在,会自动创建
        [data writeToFile:filePath atomically:YES];
    }else {
        //让offset指向文件的末尾
        [fileHandle seekToEndOfFile];
        //在文件的末尾再继续写入文件
        [fileHandle writeData:data];
        // 同步一下防止操作混乱
        [fileHandle synchronizeFile];
        //关闭文件
        [fileHandle closeFile];
    }
}
- (NSString *)getSaveFilePath{
    
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"video.mp4"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    }
    return filePath;
}

你可能感兴趣的:(避免内存爆增的方法)