writeImageToSavedPhotosAlbum leaks memory? - iphone

Been having a tough time on this one, hope someone can help! New to posting, but have found this to be my go-to site for helping me through my apps.
I have an app that takes a CGImage and copies it to the Photo Library using writeImageToSavedPhotosAlbum:orientation:completionBlock:. Functionally works great, but Instruments seems to be telling me I have a leak. Through trial and error and commenting of code, I've found that this particular line is causing the leak:
[library writeImageToSavedPhotosAlbum:myCGImage
orientation:assetOrientation
completionBlock:^(NSURL *assetURL, NSError *error){
NSLog(#"image copied to album");
}];
That line seems innocuous enough to me, so I'm really not sure why it's causing a problem. Commented out, no leak. Leave it in, I see a leak!
Here's what Instrument shows in Leaked Blocks:
Leaked Object # Address Size Responsible Library Responsible Frame
GeneralBlock-36864, 0x8c77000 36.00 KB MusicLibrary MemNewPtrClear
Here's the stack trace from Instruments, which seems to imply it's related to the photo library indeed:
0 libsystem_c.dylib calloc
1 MusicLibrary MemNewPtrClear
2 MusicLibrary ReadITImageDB
3 MusicLibrary -[MLPhotoLibrary _loadImageLibrary]
4 MusicLibrary -[MLPhotoLibrary albums]
5 PhotoLibrary -[PLPhotoLibrary albums]
6 PhotoLibrary -[PLPhotoLibrary eventAlbumContainingPhoto:]
7 PhotoLibrary -[PLPhotoLibrary pictureWasTakenOrChanged]
8 PhotoLibrary __-[PLAssetsSaver queueJobData:requestEnqueuedBlock:completionBlock:imagePort:previewImagePort:]_block_invoke_2
9 libdispatch.dylib _dispatch_call_block_and_release
10 libdispatch.dylib _dispatch_main_queue_callback_4CF$VARIANT$up
11 CoreFoundation __CFRunLoopRun
12 CoreFoundation CFRunLoopRunSpecific
13 CoreFoundation CFRunLoopRunInMode
14 GraphicsServices GSEventRunModal
15 GraphicsServices GSEventRun
16 UIKit -[UIApplication _run]
17 UIKit UIApplicationMain
18 mogofoto main /Users/Jutsu/Documents/mogofoto2/main.m:14
19 mogofoto start
I do release myCGIImage later, and library as well, and assetOrientation is simply a ALAssetOrientation. Nothing else is custom code, so I'm stumped! (I'd be happy to post my other lines of code surrounding this if that may cause the problem).
Any help is hugely appreciated!!!

I had similar code to yours:
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
NSMutableDictionary *metadata = [[NSMutableDictionary alloc] init];
/* ... set up the metadata */
[library writeImageToSavedPhotosAlbum:image.CGImage metadata:metadata
completionBlock:^(NSURL *assetURL, NSError *error)
{ NSLog(#"assetURL %#", assetURL);
[metadata release];
[library release];
}
];
And I was seeing exactly the same leak as you:
Leaked Object Address Size Responsible Library Responsible Frame
GeneralBlock-36864,0x5066000 36.00 KB MusicLibrary MemNewPtrClear
GeneralBlock-36864,0x4fd3000 36.00 KB MusicLibrary MemNewPtrClear
GeneralBlock-36864,0x4f72000 36.00 KB MusicLibrary MemNewPtrClear
GeneralBlock-36864,0x45ce000 36.00 KB MusicLibrary MemNewPtrClear
with a stack:
0 libsystem_c.dylib calloc
1 MusicLibrary MemNewPtrClear
2 MusicLibrary ReadITImageDB
3 MusicLibrary -[MLPhotoLibrary _loadImageLibrary]
4 MusicLibrary -[MLPhotoLibrary albums]
5 PhotoLibrary -[PLPhotoLibrary albums]
6 PhotoLibrary -[PLPhotoLibrary eventAlbumContainingPhoto:]
7 PhotoLibrary -[PLPhotoLibrary pictureWasTakenOrChanged]
8 PhotoLibrary __-[PLAssetsSaver queueJobData:requestEnqueuedBlock:completionBlock:imagePort:previewImagePort:]_block_invoke_2
9 libdispatch.dylib _dispatch_call_block_and_release
10 libdispatch.dylib _dispatch_main_queue_callback_4CF$VARIANT$up
11 CoreFoundation __CFRunLoopRun
12 CoreFoundation CFRunLoopRunSpecific
13 CoreFoundation CFRunLoopRunInMode
14 GraphicsServices GSEventRunModal
15 GraphicsServices GSEventRun
16 UIKit -[UIApplication _run]
17 UIKit UIApplicationMain
18 myAppName main
19 myAppName start
I can't see anything wrong with the code, but on looking at it again it seemed stupid to be allocing the ALAssetsLibrary and the NSMutableDictionary every time I wanted to write an image. I re-wrote the code to keep hold of them, and removed the release calls from the completion block, and the leak has magically gone away.
I'm not sure if any of that actually helps you very much. But it does make me wonder if there isn't actually a problem in Apple's code, which is only getting triggered in certain circumstances -- certainly I wasn't seeing a leak for every image I was writing, only some of them.

Related

Memory Leak in libsystem_c.dylib strdup

Getting memory leak in instruments when i m trying to test app. In app when i test youtube video in UIWebView it shows malloc Memory Leak in libsystem_c.dylib responsible framse showing is strdup.
-(void)LaunchVideo:(id)sender
{
self.videoURL = #"http://www.youtube.com/embed/0Xa4bHcJu8";
//VideoViewController *videoViewController = [[[VideoViewController alloc] initWithNibName:nil bundle:nil] retain];
VideoViewController *videoViewController = [[VideoViewController alloc] init];
videoViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
videoViewController.videoURL = self.videoURL;
[self presentModalViewController:videoViewController animated:YES];
[videoViewController release];
}
EDIT:
Below is the stack trace:
0 libsystem_c.dylib malloc
1 libsystem_c.dylib strdup
2 libnotify.dylib token_table_add
3 libnotify.dylib notify_register_check
4 AVFoundation -[AVPlayer(AVPlayerMultitaskSupport) _iapdExtendedModeIsActive]
6 AVFoundation -[AVQueuePlayer init]
7 MediaPlayer -[MPQueuePlayer init]
23 MediaPlayer -[UIMoviePlayerController setAutoRotationMask:]
24 QuickTime Plugin 0x89473ce
27 QuickTime Plugin 0x894f3bc
28 libdispatch.dylib _dispatch_call_block_and_release
29 libdispatch.dylib _dispatch_main_queue_callback_4CF$VARIANT$mp
30 CoreFoundation __CFRunLoopRun
32 CoreFoundation CFRunLoopRunInMode
33 GraphicsServices GSEventRunModal
34 UIKit UIApplicationMain
Anyone can tell why the leak is and what is the cause.
Thanks.
Tried googling for similar problems? I just did, and I found this:
iOS libsystem_c.dylib strdup memory leak NSZombie not working
To summarise, it may be a leak in a library you're not responsible for. If that's the case, and it's a tiny one-off leak, don't sweat it.

NavigationController / TableView memory leak in Iphone

Recently I have finished my first Iphone app and it works grate.... except for when i did a intense session using instruments to find leaks after awhile with no leaks, all of a sudden get about 1.3Kb worth. In the stack trace they all point to the exact line that I release a UIViewControler on after pushing it to the Navigation controller (Ill post this code a bit further down). The Leak seem to happen after a few time navagating through the ViewControlers and back again. I know this is a very generally question but I hope someone could point me in the right direction. I have spent a few days trying to solve this and it is starting to dive me crazy!
My app is a Navigation based one, here is how it works in a nutshell:
Starts with a UIViewControler which when a button is pressed goes to another UIViewControler containing a TableView.
From here depending on the contents of the array that populates the TableView it could go to a UIViewControler containing a PickerView then to the last UIViewControler or just go straight to the last UIViewControler bypassing the one with the PickerView.
Here is the code that the stack trace says the Leak is on:
SoundConfiger *third = [[SoundConfiger alloc] initWithNibName:#"SoundConfiger" bundle:[NSBundle mainBundle]];
[third setTitle:#"Sound Link"];
third.myData = myData;
third.selectedRow = row;
third.currentChoise = nil;
[self.navigationController pushViewController:third animated:YES];
[third release]; <---- Instruments says the leak is here on this line.
Shouldn't the NavigationController be responsible for this UIViewcontroler now? I have not called retain on third anywhere else and it only exists in this function.
I have a Bunch of Leaks from UIkit and QuartsZone. I have a screen shot bellow of some of them, in the stack traces all point to the same snippet of code, in the same function, in the same object as stated above at some point in the trace:
Here is a Link to the image as I can't post images yet: Link no longer valid
Here is the compleat stack trace from the first GeneralBlock-16 in the list. The one in bold (line 29) is the code snippet above:
0 libSystem.B.dylib malloc
1 CoreFoundation -[__NSArrayM insertObject:atIndex:]
2 CoreFoundation -[__NSArrayM addObject:]
3 UIKit -[UIView(UIViewGestures) addGestureRecognizer:]
4 UIKit -[UISwitch _commonInit]
5 UIKit -[UISwitch initWithCoder:]
6 UIKit UINibDecoderDecodeObjectForValue
7 UIKit UINibDecoderDecodeObjectForValue
8 UIKit -[UINibDecoder decodeObjectForKey:]
9 UIKit -[UIView initWithCoder:]
10 UIKit UINibDecoderDecodeObjectForValue
11 UIKit -[UINibDecoder decodeObjectForKey:]
12 UIKit -[UIRuntimeConnection initWithCoder:]
13 UIKit UINibDecoderDecodeObjectForValue
14 UIKit UINibDecoderDecodeObjectForValue
15 UIKit -[UINibDecoder decodeObjectForKey:]
16 UIKit -[UINib instantiateWithOwner:options:]
17 UIKit -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:]
18 UIKit -[UIViewController _loadViewFromNibNamed:bundle:]
19 UIKit -[UIViewController loadView]
20 UIKit -[UIViewController view]
21 UIKit -[UIViewController contentScrollView]
22 UIKit -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:]
23 UIKit -[UINavigationController _layoutViewController:]
24 UIKit -[UINavigationController _startTransition:fromViewController:toViewController:]
25 UIKit -[UINavigationController _startDeferredTransitionIfNeeded]
26 UIKit -[UINavigationController pushViewController:transition:forceImmediate:]
27 UIKit 0x6ea9b5
28 UIKit -[UINavigationController pushViewController:animated:]
29 Booby Trap -[SelectEventTypeviewcontroler ChooseThisOne] /Users/chriswyllie/Documents/Booby Trap/Booby Trap/Classes/SelectEventTypeviewcontroler.m:91
30 CoreFoundation -[NSObject(NSObject) performSelector:withObject:withObject:]
31 UIKit -[UIApplication sendAction:to:from:forEvent:]
32 UIKit -[UIApplication sendAction:toTarget:fromSender:forEvent:]
33 UIKit -[UIControl sendAction:to:forEvent:]
34 UIKit -[UIControl(Internal) _sendActionsForEvents:withEvent:]
35 UIKit -[UIControl touchesEnded:withEvent:]
36 UIKit -[UIWindow _sendTouchesForEvent:]
37 UIKit -[UIWindow sendEvent:]
38 UIKit -[UIApplication sendEvent:]
39 UIKit _UIApplicationHandleEvent
40 GraphicsServices PurpleEventCallback
41 CoreFoundation CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION
42 CoreFoundation __CFRunLoopDoSource1
43 CoreFoundation __CFRunLoopRun
44 CoreFoundation CFRunLoopRunSpecific
45 CoreFoundation CFRunLoopRunInMode
46 GraphicsServices GSEventRunModal
47 GraphicsServices GSEventRun
48 UIKit -[UIApplication _run]
49 UIKit UIApplicationMain
50 Booby Trap main /Users/chriswyllie/Documents/Booby Trap/Booby Trap/main.m:14
51 Booby Trap start
Thanks for your help in advance, I am hope I am just doing something silly and I need a fresh set of eyes to see it. Let me know If you need more info.
Well I am a Tool :)
I was not handeling the IBOutlets correctly in each viewControler.
I was not declaring each IBOutlet using #property with a retain, using "self.someLabel = nil" (to release and set to the IBOutlets to nil) in the viewDidUnload method for a memory warning and then finally releasing in in dealloc.
thus tool. lol
What I was doing was declaring was "IBOutlet UILabel *someLabel;" in the header with no #property and this was causing the leaks seen above, they don't happen right away it takes a while and when they do the stack trace and every thing dose not help to much.
They only way I found what was leaking was striping everything out of my app and I mean everything until the leak went away.
Thanks for your help Ishu Gupta, I am glad we had a outcome.
Here are the relevant link to show how to do IBOutlets correctly: What happens if I don't retain IBOutlet?
SoundConfiger *third = [[[SoundConfiger alloc] initWithNibName:#"SoundConfiger" bundle:[NSBundle mainBundle]] autorelease];
and remove
[third release]; this line.
You can fix only those leaks which comes because of your code(forget release any object or some wrong things). But some time you get extra leaks these are present in iphone sdk. Actully some of functions or properties of iPhone having leaks.so these can be fixed only when you change the use of these.
And one thing more 1.3 KB leak is not bad if it will not be increase with app operations.

Code data issue after upgrade to XCode + iOS 4.2

NSEntityDescription *entity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:managedObjectContext];
That line doesn't seem to work anymore (I'm pretty sure its that line).
I can't seem to work out whats the problem. The application worked perfectly on Xcode with iOS 4.1 and now crashes with this error in the console:
2010-12-07 17:12:27.552 SMSApp[9222:207] +[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580
2010-12-07 17:12:27.553 SMSApp[9222:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[ persistentStoreCoordinator]: unrecognized selector sent to class 0x5b14580'
*** Call stack at first throw:
(
0 CoreFoundation 0x01547be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0169c5c2 objc_exception_throw + 47
2 CoreFoundation 0x015497bb +[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x014b9366 ___forwarding___ + 966
4 CoreFoundation 0x014b8f22 _CF_forwarding_prep_0 + 50
5 CoreData 0x00e6f3ca +[NSEntityDescription entityForName:inManagedObjectContext:] + 42
6 SMSApp 0x000046b9 -[MessagesRootViewController reloadMessages:] + 146
7 SMSApp 0x00004a09 -[MessagesRootViewController viewDidLoad] + 85
8 UIKit 0x0052265e -[UIViewController view] + 179
9 UIKit 0x00520a57 -[UIViewController contentScrollView] + 42
10 UIKit 0x00531201 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48
11 UIKit 0x0052f831 -[UINavigationController _layoutViewController:] + 43
12 UIKit 0x00530b4c -[UINavigationController _startTransition:fromViewController:toViewController:] + 524
13 UIKit 0x0052b606 -[UINavigationController _startDeferredTransitionIfNeeded] + 266
14 UIKit 0x00643e01 -[UILayoutContainerView layoutSubviews] + 226
15 QuartzCore 0x010b4451 -[CALayer layoutSublayers] + 181
16 QuartzCore 0x010b417c CALayerLayoutIfNeeded + 220
17 QuartzCore 0x010ad37c _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 310
18 QuartzCore 0x010ad0d0 _ZN2CA11Transaction6commitEv + 292
19 UIKit 0x0047719f -[UIApplication _reportAppLaunchFinished] + 39
20 UIKit 0x00477659 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 690
21 UIKit 0x00481db2 -[UIApplication handleEvent:withNewEvent:] + 1533
22 UIKit 0x0047a202 -[UIApplication sendEvent:] + 71
23 UIKit 0x0047f732 _UIApplicationHandleEvent + 7576
24 GraphicsServices 0x01b2ca36 PurpleEventCallback + 1550
25 CoreFoundation 0x01529064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
26 CoreFoundation 0x014896f7 __CFRunLoopDoSource1 + 215
27 CoreFoundation 0x01486983 __CFRunLoopRun + 979
28 CoreFoundation 0x01486240 CFRunLoopRunSpecific + 208
29 CoreFoundation 0x01486161 CFRunLoopRunInMode + 97
30 UIKit 0x00476fa8 -[UIApplication _run] + 636
31 UIKit 0x0048342e UIApplicationMain + 1160
32 SMSApp 0x000025c4 main + 102
33 SMSApp 0x00002555 start + 53
)
terminate called after throwing an instance of 'NSException'
Any idea where this error is coming from or what is causing it?
Just to let you know as well, upgrading to XCode with iOS 4.2 caused some of the files to be deleted from my project. I don't know why this was, whether it was because they were linked files and not actually in the folder I dunno.
Any ideas?
Thanks
// EDIT
This method is in the AppDelegate:
- (NSManagedObjectContext *)managedObjectContext {
if (managedObjectContext_ != nil) {
return managedObjectContext_;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext_ = [[NSManagedObjectContext alloc] init];
[managedObjectContext_ setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext_;
}
// EDIT AGAIN
- (void)reloadMessages:(NSNotification *)notification {
NSLog(#"RECIEVED NEW MESSAGES TO MessagesRootViewController");
NSLog(#"%#",managedObjectContext);
// we need to get the threads from the database...
NSFetchRequest *theReq = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:self.managedObjectContext];
[theReq setEntity:entity];
threads = [NSArray arrayWithArray:[managedObjectContext executeFetchRequest:theReq error:nil]];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
if(notification != nil){ // if its been caused by a notification
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"New Message" message:#"A new message has been received" delegate:nil cancelButtonTitle:#"Thanks" otherButtonTitles:nil];
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
[alert release];
}
}
// EDIT 3
If I put this code in the applicationDidFinishLoading of my app delegate it works fine!
NSFetchRequest *theReq = [[NSFetchRequest alloc] init];
NSEntityDescription *theEntity = [NSEntityDescription entityForName:#"Thread" inManagedObjectContext:self.managedObjectContext];
[theReq setEntity:theEntity];
NSArray *theThreads = [NSArray arrayWithArray:[self.managedObjectContext executeFetchRequest:theReq error:nil]];
After having a quick look at your code I think I found a couple of parts that needed attention. I'll try and break them down below:
SMSAppAppDelegate
1) Notice that in your interface file, you declare your CoreData variables with an underscore at the end of the variable name. Then you create properties for each of the ivar without the underscore. That is all fine as long as you #synthesize them making the correct assignment, which seems to be missing from your implementation:
#synthesize managedObjectContext=managedObjectContext_;
#synthesize managedObjectModel=managedObjectModel_;
#synthesize persistentStoreCoordinator=persistentStoreCoordinator_;
DownloadContacts
1) In this class you are calling the managedObjectContext directly through the variable. I wouldn't recommend that but this is not your actual problem. Notice that you release the managedObjectContext on dealloc even though you have no ownership of it!
2) What I would do in this case is declare a property for the context and always access it via the property. Also if you rename your instance variable to include an underscore at the end you are minimising your chances of accessing it directly (i.e. without using self.) and it will make it easier for you to find where in this class you are actually doing that (there are a couple of places from memory).
So in your interface file, rename managedObjectContext ivar and declare a property:
NSManagedObjectContext *managedObjectContext_;
...
#property (nonatomic, retain) NSManagedObjectContext managedObjectContext;
And don't forget to make the assignment on #sythesize and release on dealloc, since you are using a retain property:
#synthesize managedObjectContext=managedObjectContext_;
...
[managedObjectContext_ release];
Then if you try and compile you will get two or three errors of unrecognised instance variable which is where you have to go and change it to self.managedObjectContext
MessagesRootViewController
And finally I'd recommend you go through the same process in your MessagesRootViewController but this one should still work fine as is!
See how you go and let me know if any of the above is not clear!
Cheers,
Rog
I'm assuming you're doing something like:
[ClassName persistentStoreCoordinator]
Make sure ClassName is defined and has the persistentStoreCoordinator class method. Perhaps the file that did these things got deleted?
Matt
Your database might be corrupted, try resetting the iOS simulator
by clicking on iOS Simulator>Reset contents and settings.
Edit:
It looks like you're trying to call a selector that doesn't exist. Try figuring out which files were deleted, as it seems like you have a method that is called that can't be found at runtime. Did your core data classes get erased, maybe?

Memory Leak with NSFetchedResultsController objectAtIndex

I have a memory leak while using NSFetchedResultsController objectAtIndex:
The stack frame is as follow:
0 CoreFoundation __CFDataAllocate
1 CoreFoundation __CFDataInit
2 CoreData -[NSSQLCore _prepareResultsFromResultSet:usingFetchPlan:withMatchingRows:]
3 CoreData -[NSSQLCore _newRowsForFetchPlan:selectedBy:withArgument:]
4 CoreData -[NSSQLCore newRowsForFetchPlan:]
5 CoreData -[NSSQLCore objectsForFetchRequest:inContext:]
6 CoreData -[NSSQLCore executeRequest:withContext:error:]
7 CoreData -[NSPersistentStoreCoordinator executeRequest:withContext:error:]
8 CoreData -[NSManagedObjectContext executeFetchRequest:error:]
9 CoreData _faultBatchAtIndex
10 CoreData -[_PFBatchFaultingArray objectAtIndex:]
---> 11 MyApp -[DocumentViewController tableView:heightForRowAtIndexPath:]
12 UIKit -[UISectionRowData refreshWithSection:tableView:tableViewRowData:]
13 UIKit -[UITableViewRowData rectForFooterInSection:]
14 UIKit -[UITableViewRowData heightForTable]
15 UIKit -[UITableView(_UITableViewPrivate) _updateContentSize]
16 UIKit -[UITableView noteNumberOfRowsChanged]
17 UIKit -[UITableView reloadData]
18 UIKit -[UITableView layoutSubviews]
19 QuartzCore -[CALayer layoutSublayers]
20 QuartzCore CALayerLayoutIfNeeded
21 QuartzCore CA::Context::commit_transaction(CA::Transaction*)
22 QuartzCore CA::Transaction::commit()
23 QuartzCore CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*)
24 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
25 CoreFoundation __CFRunLoopDoObservers
26 CoreFoundation __CFRunLoopRun
27 CoreFoundation CFRunLoopRunSpecific
28 CoreFoundation CFRunLoopRunInMode
29 GraphicsServices GSEventRunModal
30 GraphicsServices GSEventRun
31 UIKit UIApplicationMain
From this stack frame, it looks like the object accessed with objectAtIndex get leaked.
However, when I leave the controller, its dealloc method get called. In this method, all the objects fetched by the fetchedresultscontroller are turned into fault since I use [NSManagedObjectContext refreshObject:mergeChange].
To be complete in my description, below is the code where the leaking object is created:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
Page* page = [[self fetchedResultsController] objectAtIndexPath:indexPath];
UIImage* thumbnail = [page getThumbnail];
[[self managedObjectContext] refreshObject:page.image mergeChanges:NO];
CGFloat height = [PageCell cellImageSize:thumbnail].height + 20;
return height;
}
Any hint would be appreciated,
Thanks!
Check the code where you get the UIImage. The leak is most likely there. Where it is exactly depends on how you create the image object.
Barring more evidence, that looks more like a leak in the bowels of Core Data. File a bug.

How to ensure that UIImage is never released?

I grabbed the crash log from the iPhone:
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000c
Crashed Thread: 0
Thread 0 Crashed:
0 libobjc.A.dylib 0x30011940 objc_msgSend + 20
1 CoreFoundation 0x30235f1e CFRelease + 98
2 UIKit 0x308f4974 -[UIImage dealloc] + 36
3 CoreFoundation 0x30236b72 -[NSObject release] + 28
4 UIKit 0x30a00298 FlushNamedImage + 64
5 CoreFoundation 0x30250a20 CFDictionaryApplyFunction + 124
6 UIKit 0x30a0019c _UISharedImageFlushAll + 196
7 UIKit 0x30a00730 +[UIImage(UIImageInternal) _flushCacheOnMemoryWarning:] + 8
8 Foundation 0x3054dc7a _nsnote_callback + 178
9 CoreFoundation 0x3024ea52 _CFXNotificationPostNotification + 298
10 Foundation 0x3054b854 -[NSNotificationCenter postNotificationName:object:userInfo:] + 64
11 Foundation 0x3054dbba -[NSNotificationCenter postNotificationName:object:] + 14
12 UIKit 0x30a00708 -[UIApplication _performMemoryWarning] + 60
13 UIKit 0x30a006a0 -[UIApplication _receivedMemoryNotification] + 128
14 UIKit 0x30a005d0 _memoryStatusChanged + 56
15 CoreFoundation 0x30217410 __CFNotificationCenterDarwinCallBack + 20
16 CoreFoundation 0x3020d0aa __CFMachPortPerform + 72
17 CoreFoundation 0x30254a70 CFRunLoopRunSpecific + 2296
18 CoreFoundation 0x30254164 CFRunLoopRunInMode + 44
19 GraphicsServices 0x3204529c GSEventRunModal + 188
20 UIKit 0x308f0374 -[UIApplication _run] + 552
21 UIKit 0x308eea8c UIApplicationMain + 960
...
...
From my previous question, Can somebody give me a hand about this stacktrace in iPhone app?, I have changed my codes mainly around UIImage part. I now use [[UIImage alloc] initWithContentsOfFile ... ]. No more [UIImage imageNamed: ... ] or the like. The portion is below.
//this is a method of a subclass of UIImageView.
- (void) reviewImage: (bool) review{
NSString* st;
if (review){
NSString* origin = [NSString stringWithString: [[ReviewCardManager getInstance] getCardImageString:chosenIndex]];
NSString* stt = [origin substringToIndex: [origin length]-4];
st = [[NSString alloc] initWithString: stt];
if (myImageFlipped == nil)
myImageFlipped = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImageFlipped];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}else{
st = [[NSString alloc] initWithFormat:#"sc%d", chosenNumber];
if (myImage == nil)
myImage = [[UIImage alloc] initWithContentsOfFile: [[NSBundle mainBundle] pathForResource:st ofType:#"png"]];
[self setImage:myImage];
if (notRotated){
self.transform = CGAffineTransformRotate(self.transform, [MyMath radf:rotate]);
notRotated = false;
}
}
[st release];
}
I also have the UIImage already retained in the property.
#property (nonatomic, retain) UIImage* myImage, *myImageFlipped;
Memory Leaks have also been taken cared of. These variables are release in dealloc method.
I thought that I have successfully killed the bug, but it seems that I still have a rare occuring bug problem.
Based on the crash log, my application yells out "performMemoryWarning". I am just "alloc"-ing 13 .png images with the size 156 x 272. I'm confused. Those images shouldn't take that much memory to the point that it exceeds iPhone's RAM. Or is there something I am overlooking? Please advise.
To help you with memory issues and UIImages, you might want to use the imageNamed convience method of UIImage, from the docs:
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.
Alternatively, you might want to go this route if you still run into memory issues after switching to UIImage imageNamed, because there are some downsides to using the convinience method.
The problem is solved. I forgot to change UIImage at one place. Now, all UIImages are truly "alloc", no more autorelease.
FYI, if you are using [UIImage imageNamed: ... ], use "Simulate Memory Warning" on iPhone Simulator to see whether you are having a problem with it when the real device is low on memory.