2012-12-19 31 views
1

我该如何解决这个内存泄漏问题?我有一个NSBezierPath的集合吗?我该如何解决这个内存泄漏问题?有什么建议?我正在使用ARC。Objective-C NSImage,内存泄漏(任何建议)我正在使用ARC

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 

     // insert code here... 
     for(int j=0;j<5000;j++){ 
      NSLog(@"Hello, World!"); 
      NSSize imageSize = NSMakeSize(512, 512); 
      NSImage *image = [[NSImage alloc] initWithSize:imageSize]; 
      //draw a line: 
      for(int i=0;i<1000;i++){ 
       [image lockFocus]; 
       float r1 = (float)(arc4random() % 500); 
       float r2 = (float)(arc4random() % 500); 
       float r3 = (float)(arc4random() % 500); 
       float r4 = (float)(arc4random() % 500); 
       [NSBezierPath strokeLineFromPoint:NSMakePoint(r1, r2) toPoint:NSMakePoint(r3, r4)]; 
      } 
      //... 

      NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)]; 
      NSData *pngData = [imageRep representationUsingType:NSPNGFileType properties:nil]; 
      [image unlockFocus]; 

      NSString *jstring = [NSString stringWithFormat:@"%d", j]; 
      jstring = [jstring stringByAppendingString:@".png"]; 
      [pngData writeToFile:jstring atomically:YES]; 
     } 
    } 

    return 0; 
} 
+0

你说得对,我很新。我喜欢制作5000张带有随机线条的照片。 – user1735714

回答

4

修订的答案,现在我知道你正在使用ARC:

这可能不是你漏,但你的自动释放池越来越大与循环的每次迭代,因为自动释放池在你的循环完成之前不会清空。

你需要做的是在你的循环中使用第二个autorelease池。下面是你的代码的修改版本来说明这一点。

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 
     // insert code here... 
     for(int j=0; j<5000; j++) { 
      NSLog(@"Hello, World!"); 
      NSSize imageSize = NSMakeSize(512, 512); 
      @autoreleasepool { 
       NSImage *image = [[NSImage alloc] initWithSize:imageSize]; 
       //draw a line: 
       NSData *pngData; 
       for(int i=0;i<1000;i++){ 
        [image lockFocus]; 
        float r1 = (float)(arc4random() % 500); 
        float r2 = (float)(arc4random() % 500); 
        float r3 = (float)(arc4random() % 500); 
        float r4 = (float)(arc4random() % 500); 
        [NSBezierPath strokeLineFromPoint:NSMakePoint(r1, r2) toPoint:NSMakePoint(r3, r4)]; 
        //... 

        NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)]; 
        pngData = [imageRep representationUsingType:NSPNGFileType properties:nil]; 
        [image unlockFocus]; 
       } 

       NSString *jstring = [NSString stringWithFormat:@"%d", j]; 
       jstring = [jstring stringByAppendingString:@".png"]; 
       [pngData writeToFile:jstring atomically:YES]; 
      } 
     } 
    } 

    return 0; 
} 

虽然你似乎还有其他问题。你正在为你的文件构建一个完整的路径吗?

+0

什么错误?请详细说明。 – trudyscousin

+0

嗨,我收到错误ARC禁止显式的消息发送或发布 – user1735714

+0

@ user1735714请参阅我的编辑。 'pngData'需要在你的循环范围之外声明。 – trudyscousin