application crash after low memory warnings - iphone

my iphone application crash after raising 4 warnings of low memory, instruments is showing no memory leaks but in memory allocation live Bytes goes up to 4.7mb and Over all Bytes goes upto 79.0 MB and application crash at this point
any help will be highly appreciated
for (int i = 0; i<3; i++)
{
UIImage *rendered_image;
UIGraphicsBeginImageContextWithOptions(sub_view.bounds.size, NO, 0.0);
[appdelegate.arrimages removeAllObjects];
[appdelegate.arranimations removeAllObjects];
NSString *oldgroup = [[NSString alloc] init];
NSString *currentgroup = [[NSString alloc] init];
for(int i=0; i<[sub_view.data count]; i++)
{
oldgroup = (i>0) ? [sub_view.group objectAtIndex:(i-1)] : [sub_view.group objectAtIndex:i];
currentgroup = [sub_view.group objectAtIndex:i];
/*
IF DIFFERENT GROUP NAME RECEIVED
1-GET NEW INSTANCE OF IMAGE
2-SAVE PREVIOUS IN ARRAY
*/
if (![oldgroup isEqualToString:currentgroup])
{
rendered_image = UIGraphicsGetImageFromCurrentImageContext();
[self SaveImagesOfAnimation:[self compressImageDownToPhoneScreenSize:rendered_image]];
[appdelegate.arranimations addObject:[sub_view.anim objectAtIndex:i]];
UIGraphicsEndImageContext();
UIGraphicsBeginImageContextWithOptions(sub_view.bounds.size, NO, 0.0);
}
id element = [sub_view.data objectAtIndex:i];
color = [sub_view.fillColor objectAtIndex:i];
[color setFill];
[element fill];
[[UIColor blackColor] setStroke];
[element stroke];
}
rendered_image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self SaveImagesOfAnimation:[self compressImageDownToPhoneScreenSize:rendered_image]];
}

Increasing memory use without a leak implies that you're storing data that you never release, and you're still holding a reference to it.
This usually means that one of the data structures that will grow automatically when you put more data in it, like NSMutableArray, is to blame. They will happily hold all the data you add to them and the memory profiler won't find any leaks since items put in the NSMutableArray are - by definition - never released and not detected as leaks since there's a reference to them from the array.
Edit: For the general way to solve this if you have no obvious places to look, see the comment from #Costique at the top;
Instruments can also show the kind of objects you've allocated and
the exact stack traces, so you should be able to quickly figure it
out.

Related

UIFont fontWithName: residing on heap and never destroyed

NSMutableArray *fontsDetails=[[NSMutableArray alloc] init];
[fontsDetails addObject:[UIFont systemFontOfSize:28]];
NSArray *fontFamilies = [UIFont familyNames];
for (int i = 0; i < [fontFamilies count]; i++)
{
NSArray *fontNames = [UIFont fontNamesForFamilyName:[fontFamilies objectAtIndex:i]];
#autoreleasepool {
for (NSString *fontName in fontNames) {
[fontsDetails addObject:[UIFont fontWithName:fontName size:28]];
}
}
}
I am using this code in viewDidLoad of a controller, with this code the heap shot difference between the first and second run increases by 5mb and never comes down. (subsequent heap shots differences are lower). I am finding [UIFont fontWithName:] in the backtrace of heap shot, i ran the leak profiler and there are no leaks. All the fonts loaded are kept at heap and never destroyed. Please help me to solve this.
More likely than not, it is a cache in the system that is hanging on to the UIFont with the expectation that it will be used again.
Given that it grows once, and never again, it isn't a leak.
If you use the reference event tracker in the Allocations instrument, you can see what is retaining the font. I'd bet that you'll find an extra retain or two somewhere in the UIFont machinery.

Objective-c UIImage storage in MSMutableArray alternative, potential memory-leaks?

I am building an app for iOS 5 using ARC and I seem to be having some memory issues. Basically its taking screen-shots of a portion of the display, placing the UIImage in an MSMutableArray and then piecing the screen-shots together for one big image. Now the problem is that after doing this a couple of times the OS closes the application due to high memory usage.
Here is the snippet that pieces the UIImage's together:
UIImage* finalImage = nil;
//join the screenshot images together
UIGraphicsBeginImageContext(CGSizeMake(collage.width, collage.height));
{
int hc = 0;
for(UIImage *img in imageArr)
{
NSLog(#"drawing image at:: %i", hc);
[img drawAtPoint:CGPointMake(0, hc)];
hc+=img.size.height;
img = nil;
}
//NSLog(#"creating finalImage");
finalImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
//do something with the combined image
//remove all the objects
[imageArr removeAllObjects];
//reset class instance
[self setImageArr: [[NSMutableArray alloc] init]];
Are they any other alternatives that I could use so there isn't so much memory being used? Maybe storing a CGImageRef in the array? Are there any potential memory leaks with the above code?
Any tips, pointers would be greatly appreciated.
Thanks.
[imageArr removeAllObjects]; will remove the objects from array. No need to reset the array again with
[self setImageArr: [[NSMutableArray alloc] init]];
By doing this you are allocating a NSMutableArray object and not releasing it.
Try by removing the line [self setImageArr: [[NSMutableArray alloc] init]];
make sure you alloc and init setImageArr
if (setImageArr == nil){
setImageArr = [[NSMutableArray alloc]init];
}
else
{
[setImageArr removeAllObjects];
}
or use (if you want to init from an existing Array):
NSMutableArray *setImageArr = [[NSMtableArray]initWithArray:arrayOfImages];
Because you say it will have memory issue after doing this a couple of times. Then how about you use NSAutoreleasePool to force system release objects after your method, example below:
#autoreleasepool {
UIImage* finalImage = nil;
//join the screenshot images together
UIGraphicsBeginImageContext(CGSizeMake(collage.width, collage.height));
{
int hc = 0;
for(UIImage *img in imageArr)
{
NSLog(#"drawing image at:: %i", hc);
[img drawAtPoint:CGPointMake(0, hc)];
hc+=img.size.height;
img = nil;
}
finalImage = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
//do something with the combined image
//remove all the objects
[imageArr removeAllObjects];
//reset class instance
[self setImageArr: [[NSMutableArray alloc] init]];
}
And I also doubt there is any memory leak problem in your other codes.
Using ARC doesn't meaning without memory leak problem, maybe you store many useless objects in a global variable etc.
Maybe you should use Instruments to monitor the memory to figure out where does the memory go.
Turns out the imageArr is being cleared properly. There appears to be a memory issue somewhere else in the program.

How to fix CFRuntimeCreateInstance object leak?

I'm having unseen object leak (CFRuntimeCreateInstance) when profiling my app with instrument leak tool. I have rough imagination where the leak occurs but unable to spot it :) The call tree points me to my class method for loading an image from a spritesheet. Here is a fragment of the call tree (until leaking object CFRuntimeCreateInstance):
+[ImageCache loadImageOfType:andIndex:]
+[NSString stringWithFormat:]
_CFStringCreateWithFormatAndArgumentsAux
CFStringCreateCopy
__CFStringCreateImmutableFunnel3
_CFRuntimeCreateInstance
I'm using this helper class method for loading and caching the image. The method uses static NSMutableDictionary where it pushes loaded image for further use. My images are grouped into spritesheets, so the method reads corresponding image file and reads corresponding image area. Here is my method:
+(UIImage*)loadImageOfType:(int)type andIndex:(int)index{
UIImage *image;
if (!dict) dict = [[NSMutableDictionary dictionary] retain];
//First, trying to get already loaded image
int ind = IMAGECOUNT * type + index; //calculating the index that is used for storing image in dict
image = [dict objectForKey:[NSString stringWithFormat:#"%d", ind]]; //trying to get image
if (!image){ //if image is not loaded then read the spriteimage file
NSString *spritesheetName = [NSString stringWithFormat:#"itemsprite%d.png", type];
NSString* imagePath = [[NSBundle mainBundle] pathForResource:spritesheetName ofType:nil];
image = [UIImage imageWithContentsOfFile:imagePath];
if (image) //if spritesheet exists
{
int loopInd;
CGFloat x = 0, y = 0;
//load all images from it
for (int i=0; i<IMAGECOUNT; i++) {
UIImage *img;
loopInd = IMAGECOUNT * type + i;
CGImageRef imageRef = CGImageCreateWithImageInRect( [image CGImage], CGRectMake(x, y, ITEMIMAGESIZE, ITEMIMAGESIZE));
img = [UIImage imageWithCGImage:imageRef];
[dict setObject:img forKey:[NSString stringWithFormat:#"%d", loopInd]];
CGImageRelease(imageRef);
x += ITEMIMAGESIZE;
}
}
//set image var to be image needed
image = [dict objectForKey:[NSString stringWithFormat:#"%d", ind]];
}
return image;
}
Any suggestions, where to start?
UPDATE: I'm also having a lot of messages in debug area, all are quite similar:
__NSAutoreleaseNoPool(): Object 0x4c55e80 of class NSCFNumber autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x4c69060 of class __NSCFDictionary autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x4c6a620 of class NSCFString autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x4e75fe0 of class NSPathStore2 autoreleased with no pool in place - just leaking
__NSAutoreleaseNoPool(): Object 0x4e312d0 of class UIImage autoreleased with no pool in place - just leaking
I found the problem. At the beginning of the game, I'm preloading the images. I have a method "loadGameResourses" that loops and does multiple calls to single image loading method "loadImageOfType...". Now, I'm performing the call of ""loadGameResourses" in separate thread:
[self performSelectorInBackground:#selector(loadGameResourses) withObject:nil];
The leaks just disappeared when I replaced that with:
[self loadGameResourses];
I heard that you need to deal with UIKit stuff in the main thread, so it looks like I have picked the wrong method. Everything works as expected when using this appropriate method:
[self performSelectorOnMainThread: #selector(loadGameResourses) withObject:nil waitUntilDone: NO];
I have heard that the instrument's leak tool can report false leaks. Have you tried opening Activity Monitor while your app is running and watching the memory? If there is a leak, the amount of memory will keep getting larger and larger. Make sure you actually have a leak before you dig too deep.

Am I putting too much in my NSMutableArray? Please help!

So I am making an app really quick, and even though it isn't the best solution, it appears to be working for the most part. So I have a simple image view that pulls an image out of an NSMutableArray arr. I create the array and populate it inside of ViewDidLoad in this manner:
arr = [[NSMutableArray alloc] init];
[arr addObject:[UIImage imageNamed:#"181940jpg"]];
[arr addObject:[UIImage imageNamed:#"168026.jpg"]];
[arr addObject:[UIImage imageNamed:#"168396.jpg"]];
[arr addObject:[UIImage imageNamed:#"168493_.jpg"]];
ANd I continue doing that for 130 images. Obviously this is a big array. I don't know if this is like a really bad way to do it, but if it is, I am open to suggestions! As I go through the array with some simple back and forward buttons pulling images out of the array based on a simple counter variable things work ok until image 45-ish. The app breaks down and the console says this:
* ERROR: ImageIO 'ImageProviderCopyImageBlockSetCallback' header is not a CFDictionary...
Would it help if I broke my images up into separate arrays? Am I just putting too much into the array? What am I missing here, trust me, I am all ears.
Thanks
EDIT: Here is some more information
This is how I am sifting through the array, using a UISegmentedControl set on the top of the screen:
-(void) pickedOne{
if(segmentedControl.selectedSegmentIndex == 1){
NSLog(#"hey");
if(position < [arr count]-1){
position++;//This is my global counter variable
UIImage * img = [arr objectAtIndex:position];
[imageView setImage:img];
[img release];
}
}else if(segmentedControl.selectedSegmentIndex ==0){
if(position >0){
position--;
UIImage * img = [arr objectAtIndex:position];
[imageView setImage:img];
[img release];
}
}
}
It doesn't appear to be a problem with memory management, but then again, I don't consider myself a pro at that by any means...
In terms of the mutable array, what you put into it is just a pointer to some other object. It is those other objects you have to worry about and, yes, you have too many of them (more likely than not).
ERROR: ImageIO 'ImageProviderCopyImageBlockSetCallback'
header is not a CFDictionary...
Would it help if I broke my images up
into separate arrays? Am I just
putting too much into the array? What
am I missing here, trust me, I am all
ears.
That sounds more like you have an over-release problem and are passing something bogus to the ImageIO APIs.
And, in fact, that is exactly what you have:
UIImage * img = [arr objectAtIndex:position];
[imageView setImage:img];
[img release];
That release is spurious; it does not balance a retain anywhere in your code. objectAtIndex: does not return a retained object and the UIView will take care of retaining/releasing the image internally.
Remove that release (and the other one, too)!
You still need to worry about memory consumption. At a size of 42K each (not an unreasonable size, but entirely made up), 130 images will weigh in at ~6MB or so, prior to any decompression or other expansion that occurs as a part of storage.
The devices are quite memory constrained.

ImageIO initImageJPEG instances getting allocated and never released

Im developing an app for an iPhone and I found that the following code is causing the memory allocation to increment.
-(UIImage *)createRecipeCardImage:(Process *)objectTBD atIndex:(int)indx
{
[objectTBD retain];
// bringing the image for the background
UIImage *rCard = [UIImage imageNamed:#"card_bg.png"];
CGRect frame = CGRectMake(00.0f, 80.0f, 330.0f, 330.0f);
// creating he UIImage view to contain the recipe's data
UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
imageView.image = rCard;
[rCard release];
imageView.userInteractionEnabled = YES;
float titleLabelWidth = 150.0;
float leftGutter = 5.0;
float titleYPos = 25.0;
float space = 3.0;
float leftYPos = 0;
// locating Title label
float currentHeight = [self calculateHeightOfTextFromWidth:objectTBD.Title :titleFont :titleLabelWidth :UILineBreakModeWordWrap];
UILabel *cardTitle = [[UILabel alloc]initWithFrame:CGRectMake(leftGutter, titleYPos, titleLabelWidth, currentHeight)];
cardTitle.lineBreakMode = UILineBreakModeWordWrap;
cardTitle.numberOfLines = 0;
cardTitle.font = titleFont;
cardTitle.text = objectTBD.Title;
cardTitle.backgroundColor = [UIColor clearColor];
[imageView addSubview:cardTitle];
[cardTitle release];
leftYPos = titleYPos + currentHeight + space;
// locating brown line
UIView *brownLine = [[UIView alloc] initWithFrame:CGRectMake(5.0, leftYPos, 150.0, 2.0)];
brownLine.backgroundColor = [UIColor colorWithRed:0.647 green:0.341 blue:0.122 alpha:1.0];
[imageView addSubview:brownLine];
[brownLine release];
leftYPos = leftYPos + 2 + space + space + space;
// creating the imageView to place the image
UIImageView *processPhoto = [[UIImageView alloc] initWithFrame:CGRectMake(leftGutter, leftYPos, 150, 150)];
if((uniqueIndex == indx) && (uniqueImg.imageData != nil))
{
if([uniqueImg.rcpIden isEqualToString:objectTBD.iden])
{
objectTBD.imageData = [NSString stringWithFormat:#"%#", uniqueImg.imageData];
[recipesFound replaceObjectAtIndex:indx withObject:objectTBD];
NSData * imageData = [NSData dataFromBase64String:objectTBD.imageData];
UIImage *rcpImage = [[UIImage alloc] initWithData:imageData];
[imageData release];
processPhoto.image = rcpImage;
[rcpImage release];
}
}
else if(objectTBD.imageData != nil)
{
NSData * imageData = [NSData dataFromBase64String:objectTBD.imageData];
UIImage *rcpImage = [[UIImage alloc] initWithData:imageData];
processPhoto.image = rcpImage;
[rcpImage release];
[decodedBigImageDataPointers addObject:imageData];
}
else
{
UIImage * rcpImage = [UIImage imageNamed:#"default_recipe_img.png"];
processPhoto.image = rcpImage;
[rcpImage release];
}
NSlog(#" Process Photo Retain Count %i", [processPhoto retainCount]); // this prints a 1
[imageView addSubview:processPhoto];
NSlog(#" Process Photo Retain Count %i", [processPhoto retainCount]); // this prints a 2!!!!
//[processPhoto release]; // this line causes an error :(
// converting the UIImageView into a UIImage
UIGraphicsBeginImageContext(imageView.bounds.size);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[objectTBD release];
for(UIView *eachSubview in imageView.subviews)
{
[eachSubview removeFromSuperview];
NSLog(#"each subview retainCount %i despues", [eachSubview retainCount]);
// here I find that the processPhoto view has a retain count of 2 (all other views have their retain count in 1)
}
return viewImage;
}
When I checked at the instruments object allocation I found that the "GeneralBlock-9216" growing up.
Breaking down the row I found that every time I call this code, one instance of:
2 0x5083800 00:18.534 ImageIO initImageJPEG
is being allocated. Checking the call stack, the following line is highlighted:
UIImage * objImage = [UIImage imageWithData:imageData];
Any help to find what the error is?
As TechZen said, the imageWithXXX: methods cache the image inside of them while you run the program (though you release the instances after using). I recommend initWithXXX: and release API sets instead of imageWithXXX:.
Well, if you embed several debug log on your source code, check how many times is it called, and check the retain count of the instances.
As far as I can explain, that is all.
I hope you will solve the problem.
Does anyone have an answer for this? It's tearing me apart trying to figure out why this image information keeps lingering. I've tried every solution.
The situation:
Images get downloaded and stored to the device, then loaded with imageWithContentsOfFile (or even initWithContentsOfFile, which doesn't help either). When the view goes away, the images don't, but they don't show up as leaks, they're just this initImageJPEG Malloc 9.00 KB that never goes away and keeps ramping up.
UPDATE: I believe I've figured this out: Check to make sure everything is actually getting dealloc'd when you're releasing whatever the parents (and/or grandparents) and etc of the images are. If the parents don't get deallocated, they never let go of their children images, and whatever data was in those images sticks around. So check retain counts of parent objects and make sure that everything's going away all the way up whenever you release the view at the top.
A good way to check for this is to put NSLogs into custom classes' dealloc methods. If they never show up, that object isn't going away, even though the reference to it might, and it (and whatever its subviews and properties are) will never ever disappear. In the case of images, this means a pretty sizable allocation every time that object is generated and never deallocated. It might not show up in leaks, especially if the parent of the topmost object you're thinking you're releasing but actually aren't persists and doesn't itself ever deallocate.
I hope this helps. It'll be useful to take some time to read through your code with a fine-toothed comb to make sure you're allocating and releasing things properly. (Search for "alloc]", start at the top of the file, and work your way down to make sure you're releasing and that the release isn't inside of some if() or something.)
Also, running "Build and Analyze" might lock up your machine for a bit, but its results can be really helpful.
Good luck!
I think you're seeing UIImage cacheing images. There used there used to be a method something like initWithData:cache that let you turn the cacheing off. Now I think the system always caches the images automatically behind the scenes even after you've deallocted the specific instances.
I don't think its an error on your part. I think it's the system keeping data around in the OpenGl subsystem. Unless it causes a major leak, I don't think it is a problem.