iOS 和 Mac 上 ARC 的内存问题

Memory issues with ARC on iOS and Mac

我正在尝试将 mac 的屏幕镜像到 iphone。我在 Mac app delegate 中有这个方法来将屏幕捕获到 base64 字符串中。

-(NSString*)baseString{
CGImageRef screen = CGDisplayCreateImage(displays[0]);

CGFloat w = CGImageGetWidth(screen);
CGFloat h = CGImageGetHeight(screen);

NSImage * image = [[NSImage alloc] initWithCGImage:screen size:(NSSize){w,h}];
[image lockFocus];
NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, w, h)];
[bitmapRep setCompression:NSTIFFCompressionJPEG factor:.3];
[image unlockFocus];

NSData *imageData = [bitmapRep representationUsingType:NSJPEGFileType properties:_options];
NSString *base64String = [imageData base64EncodedStringWithOptions:0];
image = nil;
bitmapRep = nil;
imageData = nil;

return base64String;}

之后我将它发送到 iphone 并在 UIImageView 中显示它。 屏幕截图之间的延迟为 40 毫秒。一切都按预期工作,直到有足够的内存。流式传输一分钟后,它开始交换并使用 6GB RAM。 iOS 应用程序内存使用量也在线性增长。当 iOS 达到 90MB 内存时,mac 有 6GB。 即使我停止流式传输,内存也不会被释放。 我在这两个项目中都使用了 ARC。如果将其迁移到手动引用计数会有什么不同吗?
我也试过 @autoreleasepool {...} 块,但没有用。
有什么想法吗?

编辑

我的 iOS 代码在这里

NSString message = [NSString stringWithFormat:@"data:image/png;base64,%@",base64];
NSURL *url = [NSURL URLWithString:message];
NSData *imageData = [NSData dataWithContentsOfURL:url];

UIImage *ret = [UIImage imageWithData:imageData];
self.image.image = ret;

你有严重的内存泄漏。 CGDisplayCreateImage 的文档明确指出:

The caller is responsible for releasing the image created by calling CGImageRelease.

通过调用更新您的代码:

CGImageRelease(screen);

我会在创建 NSImage 之后添加它。

我们无法解决您的 iOS 内存泄漏问题,因为您没有 post 您的 iOS 代码,但我发现您的 [=29= 内存泄漏很大] 代码。

您正在调用 Core Foundation 函数,CGDisplayCreateImage。 Core Foundation 对象不受 ARC 管理。如果 Core Foundation 函数的名称中包含 "Create"(或 "copy"),那么它会跟在“create rule”之后,您有责任在使用完后释放返回的 CF 对象。

一些 CF 对象有特殊的释放调用。对于那些不这样做的人,只需致电 CFReleaseCGImageRef 有一个特殊的发布电话,CGImageRelease()

您需要对 CGImageRelease(screen) 的相应调用,可能在对 initWithCGImage 的调用之后。