Question

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?

Était-ce utile?

La 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);
}

Autres conseils

I'm assuming that you're not using ARC here.

You seem to have misunderstood what an autorelease pool does. It doesn't magically release objects by its own prerogative (that's what ARC is for!). You add objects to the pool — either by using autorelease (in managed retain/release mode) or by using a convenience constructor that autoreleases for you — and when it's destroyed, the pool will release each object once for every time that objet was added to the pool. The method you are using to create the objects here, alloc, returns an object that you own, so you must explicitly release your ownership the object.

Just add to the bottom of your loop:

[image release];
[bitmapRep release];
CGImageRelease(image1);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top