drawViewHierarchyInRect导致VM CG图像内存泄漏

时间:2014-09-30 14:26:32

标签: objective-c ipad memory-leaks

我有一个函数,它接受界面的屏幕截图并将其保存到实例属性(称为self.interfaceScreenshot)。

-(void)takeInterfaceScreenshot{
   // Iterate over every window from back to front

   for (UIWindow *window in [[UIApplication sharedApplication] windows])
   {
       if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
       {
           UIGraphicsBeginImageContext([window bounds].size);
           [[self view] drawViewHierarchyInRect:[window bounds] afterScreenUpdates:YES];
      }
  }

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  if(self.interfaceScreenshot != nil){
      self.interfaceScreenshot = nil;
  }

  self.interfaceScreenshot = image;
}

但是我在Instruments Profiler中看到,每次调用此函数时,都会有一个额外的持久化实例泄漏在VM:CG Image部分的分配统计信息中:

enter image description here

我正在使用iOS7。

1 个答案:

答案 0 :(得分:0)

经过一些试验后,我发现错误是错误是在循环中有UIGraphicsBeginImageContext([window bounds].size);。这很好用:

-(void)takeInterfaceScreenshot{

  UIGraphicsBeginImageContext([window bounds].size);

  // Iterate over every window from back to front
  for (UIWindow *window in [[UIApplication sharedApplication] windows])
  {
      if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen])
      {
         [[self view] drawViewHierarchyInRect:[window bounds] afterScreenUpdates:YES];
      }
   }

   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if(self.interfaceScreenshot != nil){
       self.interfaceScreenshot = nil;
   }

   self.interfaceScreenshot = image;
}