在iPhone临时文件写作中的竞争条件(?)

mtr*_*trc 0 iphone file-io objective-c race-condition

我正在iPad模拟器中创建一些临时文件.要测试我的文件创建,我创建文件然后再读回来.以下是一些显示此代码的代码:

-(NSString *) writeToTempFile:(UIImage*) image{
NSString *path = [self createTemporaryFile];
NSLog(@"path: %@", path);
NSData *data = UIImageJPEGRepresentation(image, 1);
[data writeToFile:path atomically:YES]; 
free(data);
return path;
}

-(UIImage *) readTempFile:(NSString *) path{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}
Run Code Online (Sandbox Code Playgroud)

在最终函数将UIImage写入相册之前,我会一个接一个地调用这些方法.

UIImageWriteToSavedPhotosAlbum(image2, self, nil, nil);
Run Code Online (Sandbox Code Playgroud)

问题是,这总是在第三次执行时崩溃我的应用程序.第一次和第二次成功完成所有这些并存储到相册.第三次它崩溃回家.有任何想法吗?

ken*_*ytm 6

NSData *data = UIImageJPEGRepresentation(image, 1);
[data writeToFile:path atomically:YES]; 
free(data);
Run Code Online (Sandbox Code Playgroud)

从UIImageJPEGRepresentation返回的NSData是-autoreleased.没有必要free().它是错误的,以free()任何Objective-C对象-发送一个-release消息,而不是.

请仔细阅读" 内存管理编程指南".