NSString memory leak? - objective-c

I'm turning around and around with the following code giving me a memroy leak in the pics object apparently linke to the object imageName.
for (int i = 0;i<[potatoesIndexesArray count];i++){
int imageNumber = [[potatoesIndexesArray objectAtIndex:i]intValue];
NSString *imageName = [[NSString alloc] initWithFormat:#"texture%d",imageNumber];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:#"png"]];
//UIImage *imageHighlighted = [[UIImage alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:#"png"]];
NSArray *pics = [[NSArray alloc] initWithObjects:
[self maskImage:image withMask:[mainDelegate.masksArray objectAtIndex:i]],
[self maskImage:image withMask:[mainDelegate.masksArray objectAtIndex:i]],
imageName,
nil]; // pics becomes owner of objects
[textures addObject:[pics retain]]; //textures becomes owner of pics. as a release occurs later. we must retaint pics to keep it available in textures.
[imageName release];
[image release];
[pics release];
//[imageHighlighted release];
}
I've read the Apple doc on memory management bu I can't find what I did wrong there ... any idea ??
Cheers,
Tibi.

If textures is a NSMutableArray, then your [textures addObject:] call already sends a retain to pics. So, the code should be:
[textures addObject:pics];

Related

What causes a "Virtual Memory exhausted" error?

Alright.. Here's the thing.. I am building an app in which when the user taps on download button it downloads a bunch on images (296, to be exact).
In simulator everything works flawless, on my iPhone (4S) on around 100th image it crashes with error:
malloc: * mach_vm_map(size= "some random number") failed (error code= 3)* error: can't allocate region
libBacktraceRecording.dylib: allocate_free_list_pages() -- virtual memory exhausted!
Here's the code I wrote for downloading those images:
-(void)getData
{
NSError *error;
int i;
NSArray *brojLinije = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"linije" ofType:#"plist"]];
NSArray *urlSlike = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"urlSlike" ofType:#"plist"]];
NSArray *pocetno = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"pocetno" ofType:#"plist"]];
NSArray *sortiranje = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"sort" ofType:#"plist"]];
NSArray*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *desktopDir = [paths firstObject];
UIImage *image1 = [[UIImage alloc] init];
for (i = 0; i<296; i++) {
NSString *brojLinije1 = [NSString stringWithFormat:#"%#",[brojLinije objectAtIndex:i]];
NSString *pocetno1 = [NSString stringWithFormat: #"%#", [pocetno objectAtIndex:i]];
NSString *tableSort = [NSString stringWithFormat: #"%#", [sortiranje objectAtIndex:i]];
image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: #"http://www.busevi.com/images/stories/Red-Voznje/Gradski-Prevoz-BG/linija.%#.png", [urlSlike objectAtIndex:i ] ]]]];
NSData *data1 = [NSData dataWithData:UIImageJPEGRepresentation(image1, 0.1)];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
NSString *pngFilePath = [NSString stringWithFormat:#"%#%#.jpg",desktopDir,[urlSlike objectAtIndex:i]];
[data1 writeToFile:pngFilePath atomically:YES];
[newManagedObject setValue:brojLinije1 forKey:#"brojLinije"];
[newManagedObject setValue:data1 forKey:#"imageData"];
[newManagedObject setValue:pocetno1 forKey:#"pocetnoStajaliste"];
[newManagedObject setValue:tableSort forKey:#"sort"];
NSLog(#"%d / 296", i);
}
[self.managedObjectContext save:&error];
}
Only thing I know is that the image allocation frequency (too much allocating and no time to automatically release) is making the problem, AND that I have tried every method I know so far, AND I HAVE watched A LOT of "Instruments" app tutorials and only one helped (to find the source of filling virtual memory) but I still can't solve my problem.
You can use a local autorelease pool inside of the loop to immediately release any objects that were created in the body of the loop.
for (i = 0; i<296; i++) {
#autoreleasepool {
// loop body goes here...
}
}
While using SDWebImage framework I encountered a lot of bugs and unanswered crashes from the app. SDWebImage is awesome if the count of images that are about to be downloaded is lower that, let's say 50. Because, when downloading one by one image that are showed in TableViewCell + fast scrolling (fast flicking), the app receives memory warning a couple of times while the TableView is still scrolling (SDWebImage will clear memory ONLY when TableView is slowly scrolling or not scrolling at all) so it crashes the app.
So my only solace with app crashing while downloading 300+ images was simple Apple's method called dispatch_async. More about it here.
And this is how I solved my problem (I just had to move everything from my original -(void)getdata method to dispatch_async block. DONE!
So now it looks like this:
-(void)getData {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
slike = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"slike" ofType: #"plist"]];
brojevi = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"linije" ofType:#"plist"]];
pocetnaStajalista = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"pocetno" ofType:#"plist"]];
sort = [[NSArray alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:#"sort" ofType:#"plist"]];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Linija" inManagedObjectContext:self.managedObjectContext];
NSString *brojLinije;
NSString *pocetnoStajaliste;
NSString *sortiranje;
NSData *data;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.png"];
for (int i = 0; i<314; i++) {
NSManagedObject *novaLinija = [[NSManagedObject alloc]initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
brojLinije = [NSString stringWithFormat:#"%#",brojevi[i]];
pocetnoStajaliste = [NSString stringWithFormat:#"%#",pocetnaStajalista[i]];
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat: #"http://www.busevi.com/images/stories/Red-Voznje/Gradski-Prevoz-BG/linija.%#.png",slike[i]]]];
[data writeToFile:filePath atomically:YES];
sortiranje = [NSString stringWithFormat: #"%#", sort[i]];
[novaLinija setValue:data forKey:#"slikaLinije" ];
[novaLinija setValue:brojLinije forKey:#"brojLinije"];
[novaLinija setValue:pocetnoStajaliste forKey:#"pocetnoStajaliste"];
[novaLinija setValue:sortiranje forKey: #"sort"];
NSLog(#"%d / 314", i+1);
NSError *error;
[self.managedObjectContext save:&error];
} }
Hope this helps others with same problem. Good Luck and Happy Coding!
Used all of your and my suggestions and possible solutions, but, I'm sorry, none worked.
The point in this case, when app needs to download A LOT of photos, you really should use SDWebImageDownloader Class Reference.
I know It's frustrating to change the whole method and to realize the previous method (of downloading photos) is useless, so HERE is the tutorial and example on how to use SDWebImageDownloader Class. Good Luck.

Where the Memory is Leaking because showing leakage

In my Code showing 2 places memory leakage please see and Help me.
1.FIRST
UIButton *push = (UIButton *)sender;
NSString *string = [NSString stringWithFormat:#"%#",[push currentTitle]];
NSArray *chunks = [[NSArray alloc]initWithArray:[stringcomponentsSeparatedByString:#"-"]];
list = [[NSMutableArray alloc]initWithArray:chunks];
(NSMutableArray *list;)
[chunks release];
2.SECOND
Here is The Source Code First
NSAutoreleasePool *pool = [NSAutoreleasePool new];
NSURL *url = [[NSURL alloc]initWithString:#"http://www/absdf.com/myXML.xml"];
self.parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
[parser release];
[url release];
[pool drain];
while i am excuting this code and with this Instruments Tools on line number : 2 show memory leakage with heaviest backtraces.
So please let know the Reason .?
In addition to the other answers your pool should be released
NSAutoreleasePool *pool = [NSAutoreleasePool new];
//... then
[pool release];
Obviously, list = [[NSMutableArray alloc]initWithArray:chunks]; is never released.
self.parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
alloc/init returns a retained object, and if you your parser property is declared with retain attribute, then you are over retaining it. It should be:
self.parser = [[[NSXMLParser alloc]initWithContentsOfURL:url] autorelease];
P.S. Make sure you are doing proper memory management to your list instance variable. Just to be sure you better use properties.
list should be release somewhere, maybe in dealloc
- (void)dealloc {
[list release];
[super dealloc];
}
parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
or
NSXMLParser *tempParser = [[NSXMLParser alloc]initWithContentsOfURL:url];
self.parser = tempParser;
[tempParser release];

iOS: Issue Saving Photo

I'm very new to Objective-C, and am having some beginner issues. I have an application that has an area that is supposed to behave somewhat like a photo gallery. The user chooses a picture from their camera roll, and the photos get displayed in UIImageViews. I'm trying to save the image that they select. I have 9 UIImageView's, and the issue is that when I select a different photo for each UIImageView, close and relaunch the app, the other 8 UIImageViews display the photo that is stored in the first image view. Here is the code that I'm working with:
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename9];
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView2.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView3.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView4.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView5.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView6.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView7.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView8.image)];
self.imageData = [NSData dataWithData:UIImagePNGRepresentation(imageView9.image)];
[self.imageData writeToFile:[self dataFilePath] atomically:YES];
NSLog(#"The image is: %#", [[imageView image] description]);
NSLog(#"dataFilePath is: %#", [self dataFilePath]);
}
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
NSLog(#"FilePath: %#", filePath);
NSLog(#"Image: %#", imageView);
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *vdlData = [[NSData alloc] initWithContentsOfFile:filePath];
imageView.image = [[UIImage alloc] initWithData:vdlData];
imageView2.image = [[UIImage alloc] initWithData:vdlData];
imageView3.image = [[UIImage alloc] initWithData:vdlData];
imageView4.image = [[UIImage alloc] initWithData:vdlData];
imageView5.image = [[UIImage alloc] initWithData:vdlData];
imageView6.image = [[UIImage alloc] initWithData:vdlData];
imageView7.image = [[UIImage alloc] initWithData:vdlData];
imageView8.image = [[UIImage alloc] initWithData:vdlData];
imageView9.image = [[UIImage alloc] initWithData:vdlData];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
I'm trying to figure out what I need to change to get the UIImageViews to display the correct pictures, rather than them all displaying the same picture. This is probably a simple fix, but any help would be greatly appreciated, thanks!
Okay, here's how I would do it:
Use NSUserDefaults to save your images as a mutable array:
ViewController.h
#property(retain) NSUserDefaults *user;
ViewController.m
#synthesize user;
- (void)viewWillAppear:(BOOL)animated
{
self.user = [NSUserDefaults standardUserDefaults];
Edit
NSMutableArray* array = [[self.user objectForKey:#"images"]mutableCopy];
while(array == nil)
{
[self.user setObject:[NSMutableArray arrayWithObject:#""] forKey:#"images"]
array = [[self.user objectForKey:#"images"]mutableCopy];
NSLog(#"%#",#"attempting to create an array to store the images in");
}
End Edit
}
- (void)applicationDidEnterBackground:(UIApplication*)application {
NSLog(#"Image on didenterbackground: %#", imageView);
NSMutableArray* array = [NSMutableArray arrayWithObject:[NSData dataWithData:UIImagePNGRepresentation(imageView.image)]];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView2.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView3.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView4.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView5.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView6.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView7.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView8.image)];
[array addObject:[NSData dataWithData:UIImagePNGRepresentation(imageView9.image)];
[self.user setObject:array forKey:#"images"];
}
- (void)viewDidLoad
{
NSMutableArray* array = [[self.user objectForKey:#"images"]mutableCopy];
EDIT
if(array.count == 9)
{
imageView.image = [[UIImage alloc] initWithData:[array objectAtIndex:0]];
imageView2.image = [[UIImage alloc] initWithData:[array objectAtIndex:1]];
imageView3.image = [[UIImage alloc] initWithData:[array objectAtIndex:2]];
imageView4.image = [[UIImage alloc] initWithData:[array objectAtIndex:3]];
imageView5.image = [[UIImage alloc] initWithData:[array objectAtIndex:4]];
imageView6.image = [[UIImage alloc] initWithData:[array objectAtIndex:5]];
imageView7.image = [[UIImage alloc] initWithData:[array objectAtIndex:6]];
imageView8.image = [[UIImage alloc] initWithData:[array objectAtIndex:7]];
imageView9.image = [[UIImage alloc] initWithData:[array objectAtIndex:8]];
}
END EDIT
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:app];
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.user = nil;
}
This way, you will not lose the images or data, they will be stored and easily accessed, and they will not disappear even if you update your app.
Cheers!
Before I start with the solution, I have to warn you that the way you're doing this isn't the right one. I suggest that you start learning iOS development from the ground up. Apple's own documentation is a pretty good start. http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Introduction/Introduction.html
Now, back to your question. What you do here is save only one image, not all 9 of them. You set self.imageData always with each image you process and you overwrite its previous value, making only the last image to be saved to file.
So, in order to make your code working, you would have to use an imageData object for each image view, then write that data object to file.
In your case, it's probably best to optimize the code by using loops, instead using multiple objects (like imageView, imageView2, ...).
Also, make sure that you take care of your memory. e.g. imageView.image is allocated but not released.
Well, I see two issues. First and foremost, in viewDidLoad, all your images are getting initWithData:vdlData... so they're all getting the same data. That's why they're all the same.
Also, when you're trying to save them, in ...didEnterBackground, you are overwriting the value of imageData over and over again... when you save it, it's just the last one you've assigned to imageData. You probably want to create an NSArray, and store them in there, pulling them out of the array in viewDidLoad.

iOS memory management UIImage

if UIImage is an autorelease object, why when I analyze does it complain that on the 2nd line below there is a potential leak stored to image:
NSData *data = [[NSData alloc] initWithContentsOfURL: ImageURL];
UIImage *image = [[UIImage alloc] initWithData: data];
[data release];
// Do we want to round the corners?
image = [self roundCorners: image];
// Is it PNG or JPG/JPEG?
// Running the image representation function writes the data from the image to a file
if([ImageURLString rangeOfString: #".png" options: NSCaseInsensitiveSearch].location != NSNotFound)
{
[UIImagePNGRepresentation(image) writeToFile: uniquePath atomically: YES];
}
else if(
[ImageURLString rangeOfString: #".jpg" options: NSCaseInsensitiveSearch].location != NSNotFound ||
[ImageURLString rangeOfString: #".jpeg" options: NSCaseInsensitiveSearch].location != NSNotFound
)
{
[UIImageJPEGRepresentation(image, 100) writeToFile: uniquePath atomically: YES];
}
Why do you say your UIImageĀ is autoreleased? I see only
UIImage *image = [[UIImage alloc] initWithData: data];
Use instead
UIImage *image = [[[UIImage alloc] initWithData: data] autorelease];
As an alternative you may use:
UIImage *tmp = [[UIImage alloc] initWithData: data];
UIImage *image = [self roundCorners: tmp];
[tmp release];
(assuming roundCorners returns an autoreleased object).
In your code, on the second line, your UIImage isn't autoreleased. As soon as you use alloc/init methods, you're retaining. Using a convenience method like imageNamed: creates an auto released object.

Objective-C Memory Management Alchemistry: Code causes a leak after being put in a class

I came to Objective-C from C++ so I still sometimes has problems understanding memory management of Objective-C. I have a following problem now - XCode Analyzer tells me that object *data causes leaks further in code.
- (void)loadSettings
{
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSData *data = [[NSMutableData alloc]
initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]
initForReadingWithData:data];
// object *data is no longer referenced at this point and has a retain count of +1 (object leaked)
AppData *settingsData = [unarchiver decodeObjectForKey:kDataKey];
if (nil != settingsData)
{
customerVoiceActive = settingsData.customerVoice;
}
[unarchiver finishDecoding];
[unarchiver release];
[settingsData release];
}
}
What drives me crazy is that exactly the same code (except naming) perfectly works and causes no leaks, being placed in applicationDidFinishLaunching:
//load app data
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSData *data = [[NSMutableData alloc]
initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]
initForReadingWithData:data];
AppData *appData = [unarchiver decodeObjectForKey:kDataKey];
bCustomerVoice=appData.customerVoice;
[unarchiver finishDecoding];
[unarchiver release];
[data release];
}
What's the difference?
In code sample 1) you release settingsData, while in codesample 2) you are releasing data . Changing that line should solve your issue.
You forgot to release NSData *data.
Add the following line after [settingsData release];:
[data release];
The "exact same" code contains an extra line:
[data release];
settingsData should NOT be released, because it was not obtained through a method that implies that you own the returned object. However, you MUST release data, because you allocated it yourself, and this implies ownership.