Search code examples
objective-cxcodememory-leaksscreenshotautorelease

Objective C @autoreleasepool infinite loop taking screenshots


I have a memory issue with small app taking infinite amount of screenshots every X milliseconds and displaying them in a imageview. Even with autorelease, it floods the memory very quickly. Here's the code:

- (void)draw {
    do {
        @autoreleasepool {
            CGImageRef image1 = CGDisplayCreateImage(kCGDirectMainDisplay);

            NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:image1];
            NSImage *image = [[NSImage alloc] init];
            [image addRepresentation:bitmapRep];
            _imageView.image = image;
            [NSThread sleepForTimeInterval:1];
        }
    }while(true);
}

Any ideas?


Solution

  • you need to release the image using CGImageRelease

    - (void)draw {
        do {
            @autoreleasepool {
                CGImageRef image1 = CGDisplayCreateImage(kCGDirectMainDisplay);
    
                NSBitmapImageRep *bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage:image1];
                NSImage *image = [[NSImage alloc] init];
                [image addRepresentation:bitmapRep];
                _imageView.image = image;
                CGImageRelease(image1);   // release the image
                [NSThread sleepForTimeInterval:1];
            }
        }
        while(true);
    }