views:

127

answers:

3

Hi, I've the following code which causes crashes after sometime as i've set the below code in a timer:

CGImageRef cgImage = UIGetScreenImage();
[array addObject:(id)cgImage];
CGImageRelease(cgImage);

Where initiallly i've declared array as:

array = [[NSMutableArray alloc] init];

The timer goes well till 10 seconds as timer is of 1/10 seconds after 10 seconds it crashes.

I think the application crashes because of EXC_BAD_EXCESS but dont know how to solve. Can anybody help in solving the problem?

Thanks in Adv.

A: 

addObject: will raise an exception if the object is nil. Try this:

array = [[NSMutableArray alloc] initWithCapacity:1]; //designated initializer
CGImageRef cgImage = UIGetScreenImage();
if(cgImage)
{
    [array addObject:cgImage];
    CGImageRelease(cgImage);
}
Elise van Looij
I'm continously adding to array so how can i initialize with capacity of 1. Is there any other way to implement this logic?
sujyanarayan
The capacity of 1 is just an initial memory reserve, NSMutableArray will expand as needed. If you know that very soon after the allocation, you will be adding at least twelve objects, then use initWithCapacity:12. The idea is to give NSMutableArray a reasonable estimation of the amount of memory it should reserve, it's not the maximum capacity.
Elise van Looij
A: 

Are you sure you're supposed to be releasing cgImage?

I don't see documentation for UIGetScreenImage(), but if it follows the Create Rule, I would not expect you to need to release the object (because the function does not have "Create" or "Copy" in its name).

EDIT: I've since found several references that say that you do need to release the image, despite the name of the function. (Which has apparently been renamed UICreateScreenImage() in the 3.2 SDK.

David Gelhar
A: 

From the Apple Developer Forum to UIGetScreenImage():

As you use this function, please note that it returns a retained CGImageRef and manage your memory accordingly.

schaechtele