xcode 将 NSImage 转换为 NSData
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11719747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting NSImage to NSData
提问by hockeyman
I get NSImage like that:
我得到这样的 NSImage:
imageG = [[[NSImage alloc] initWithSize:NSMakeSize(imageN.size.width, imageN.size.height)] autorelease];
[imageG addRepresentation:[NSCIImageRep imageRepWithCIImage:result]];
And the result is really good. So there are no mistakes i think. And then I try to convert this image to NSData like that:
结果真的很好。所以我认为没有错误。然后我尝试将此图像转换为 NSData 像这样:
NSData *imgData = [imageG TIFFRepresentation];
And i am getting error:
我收到错误:
Thread 1: EXC_BAD_ACCESS (code=13, adress=0x0)
at that line. Where is my mistake?
在那条线上。我的错误在哪里?
采纳答案by arbales
You need to retain
your objectas you create it, it appears it's being reallocated by the time you ask it for its data reorientation.
您在创建对象时需要retain
使用它,当您要求它进行数据重新定向时,它似乎已被重新分配。
imageG = [[[[NSImage alloc] initWithSize:NSMakeSize(imageN.size.width, imageN.size.height)] retain] autorelease];
imageG = [[[[NSImage alloc] initWithSize:NSMakeSize(imageN.size.width, imageN.size.height)] retain] autorelease];
Generally if you create an object from an initializer - not a factory method - you should retain and auto release it. The benefits of doing so, and other good tips on memory management can be found at: Why should a self-implemented getter retain and autorelease the returned object?
通常,如果您从初始化程序创建对象 - 而不是工厂方法 - 您应该保留并自动释放它。这样做的好处以及其他关于内存管理的好技巧可以在以下位置找到:为什么自实现的 getter 应该保留并自动释放返回的对象?
It's also to handy to note that BAD_ACCESS
indicates a memory issue of some kind.
值得注意的是,这BAD_ACCESS
表明某种内存问题。