Application Crash due to Memory issue / MBProgressHUD Indicator - iphone

I have a strange issue .
I am currently working on a mail app and it used to crash randomly without and error or logs in my console . I checked my Crash Log it showed me Low Memory warning with jettisoned written next to my App.
So I suspect it's an memory issue and went back to trace my memory usage of my application.
I used allocation instrument to detect the overall usage and my application crashed when it's heap size was just 4.59 MB.
Instruments point towards a function where I am using MBProgressHUD indicator.
The culprit is this one line :
[appDelegate showHUDActivityIndicatorOnView:self.parentViewController.view whileExecuting:#selector(refreshInBackground) onTarget:self withObject:nil withText:#"Loading"];
If I replace this with
[self refreshInBackground] everything works fine no issues ..
Here is the code :
-(void) showHUDActivityIndicatorOnView:(UIView*)view whileExecuting:(SEL)method
onTarget:(id)target withObject:(id)object withText:(NSString*)label{
self.HUD = [[MBProgressHUD alloc] initWithView:view] ;
self.navigationController.navigationItem.hidesBackButton = YES;
[view addSubview:self.HUD];
self.HUD.delegate = nil;
self.HUD.labelText = label;
[self.HUD showWhileExecuting:method onTarget:target withObject:object animated:YES];
}
self.HUD is a property which is being retained.
With a slight modification is showWhileExecuting method as follows :
- (void)showWhileExecuting:(SEL)method onTarget:(id)target withObject:(id)object animated:(BOOL)animated {
MyAppdelegate *appDelegate = (MyAppdelegate *)[UIApplication sharedApplication].delegate;
if(!appDelegate.isRequestActive)
{
methodForExecution = method;
targetForExecution = [target retain];
objectForExecution = [object retain];
// Launch execution in new thread
taskInProgress = YES;
[NSThread detachNewThreadSelector:#selector(launchExecution) toTarget:self withObject:nil];
// Show HUD view
[self show:animated];
}
else {
[self done];
}
}
currently I have removed this from my app and it works fine now and it does not crashes even with the usage of 20 - 30 MB heap Memory .
I am not looking for an specific answer or solution here . What I am looking for ways to debug / techniques to debug the issue so that I can get to know what caused my app to crash .
Is it memory overflow . If that's the case then how can I use 20-30 MB right now.
If it's not an memory issue why does my crash reporter shows jettisoned next to my App name .
the culprit line ([appDelegate showHUDActivityIndicatorOnView:self.parentViewController.view whileExecuting:#selector(refreshInBackground) onTarget:self withObject:nil withText:#"Loading"])
Every time when I call this function some memory increases , because of some elements being cached . But when memory reached 4.5 MB ...this line cause it to crash
How do I get to the root cause of this issue . How do I figure out why iOS is killing my app the reason for jettisoned written next to my app
Any help or suggestions would be really appreciated .

Ok. The problem is I was adding the HUD progress bar on my view using
[view addSubview:self.HUD];
I forgot to remove it from the super view in its delegate method:
- (void)hudWasHidden:(MBProgressHUD *)hud
{
// Remove HUD from screen when the HUD was hidded
[HUD removeFromSuperview]; // app crashes at 4.59 MB if you comment this
[HUD release];
HUD = nil;
}
Because of this several views were added every time on one UIView ... I guess there is an upper limit for the number of child subviews on top of each UIView .... apple should mention this in their documentation ...

If you're not using ARC, you have for sure a leak every time you assign the property:
self.HUD = [[MBProgressHUD alloc] initWithView:view] ;
Change your code in this way:
MBProgressHUD *progressHUD = [[MBProgressHUD alloc] initWithView:view] ;
self.HUD = progressHUD;
[progressHUD release];

Related

ZBar API Embedded Scanner Blur issue

I am using ZBar iPhone SDK in one of my projects (iOS SDK 5.1 ,XCode 4.4.1 and device running iOS 5.5.1). I am using the embedded scanner from the examples provided in the SDk itself.
Now the issue which I am facing is that I successfully scan a bar code and move to another view controller ( using navigation controller). When I come back (pop the second view controller) the scanner i.e the ZBarReaderView doesn't scan the subsequent bar codes , infact the overlay shows a blur image of the scanned barcode and is never able to scan it properly.
This is what all I have implemented . In BarScannerViewController.h I have declared
ZBarReaderView* readerView;
with property
#property (nonatomic , retain) IBOutlet UIImageView* imgvScannedBarCode;
Now this is connected to one of the views in xib.
Finally I use set up the required methods as follows -
- (void)viewDidLoad {
[super viewDidLoad];
// the delegate receives decode results
readerView.readerDelegate = self;
[readerView start];
}
- (void) viewDidAppear: (BOOL) animated {
// run the reader when the view is visible
[activityIndicatorScanning startAnimating];
[readerView start];
}
- (void) viewWillDisappear: (BOOL) animated {
[activityIndicatorScanning stopAnimating];
[readerView stop];
}
With all this set up when I scan any bar code say EAN123 for the first time I get the call back in
- (void) readerView: (ZBarReaderView*) view
didReadSymbols: (ZBarSymbolSet*) syms
fromImage: (UIImage*) img
{
// do something useful with results
ZBarSymbol *symbol = nil;
for(symbol in syms) {
barCodeFound = YES;
break;
}
// EXAMPLE: do something useful with the barcode data
NSLog(#"%#",symbol.data);
}
but on subsequent runs (After I push a view and come back on this screen again) I get blurred view.
Am I missing something here ? Any help/Suggestion/Comments would be helpful.
Here's the code that I use to start (and endlessly restart) the scanner. Interestingly, I note that I never stop the scan, but it works very reliably.
- (void) startScan
{
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
ZBarImageScanner *scanner = reader.scanner;
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
// present and release the controller
[self presentViewController:reader animated:YES completion:nil]; // Modal
[reader release];
}
I could solve the Blur issue by reconfiguring the SDK in my project. I followed the embedded scanner example as provided on ZBarSDk. I guess I might have missed some essential settings while configuring it earlier.

memory crash when i try to stopAnimating UIActivityIndicatorView

When ever i am trying to update the UIActivityIndicatorView from thread . the app is getting crashed by throwing an exception
modifying layer that is being finalized - 0x7e177fd0
-[CALayer removeAnimationForKey:]: message sent to deallocated instance 0x7e177fd0 .
when i try track the memory leaks form the mallocDebugger tool .
this crash is not happening at all the time happening 1 out of 10
please help me out rom this memory issue
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
[autoRechargeCell addSubview:activityIndicator];
[self.activityIndicator startAnimating];
if( [PennyTalkAPI getBalanceInfoForAccount:appDelegate.accountNumber withPIN:appDelegate.pinNumber])
{
[autoRechargeCell.switchField setOn:[[NSUserDefaults standardUserDefaults] boolForKey:#"AutoRecharge"]];
[self.activityIndicator stopAnimating]; <<<<<<<<<<<<<<<<<<<<<<
}
else
{
[self.activityIndicator stopAnimating];
}
[pool release];
This is the code i have written
Without looking at code and seeing error I assume you release your Activity Indicator and then you are trying to access it to animate..
Solution: Declare UIActivityIndicator object in .h file synthesize and release it in -(void)dealloc method.
This is either a double release error, or a dangling pointer. You should enable zombie detection in your Scheme's configuration, and try the Zombies instrument in Instruments.

stop indicator in asynchronous downloading

I am adding all image downloading operation into Nsoperationqueue. But some times indicator will display for forever. Here I have paste some of my code. Is there any way to stop indicator. Here I am checking "operationcount". If it will become 1 means its last operation so I am stoping indicator but sometimes its not working any help will be appreciated.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:self.iconImage];
myobject.iconImage = [[UIImage alloc] initWithContentsOfFile:self.filename];
myobject.isImageLoaded = YES;
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
finished = YES;
executing = NO;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
NSLog(#"finsh");
AboutUSAppDelegate *appdel=(AboutUSAppDelegate*)[UIApplication sharedApplication].delegate;
NSLog(#"%d",[appdel.queue operationCount]);
if ([appdel.queue operationCount]==1) {
//code to stop indicator
//Using main thread
}
Here I have added Nslog for operation count but sometimes it prints last value 2 two times. other values only 1 times.
You need to ensure that all UI calls are made on the main thread of operation. So showing the activity indicator, making it spin, stopping it and hiding it all need to be done on the main thread.
A reasonable way to achieve this is to expose methods in your view controllers to do it and from inside your Operation code call them on the main :-
Look up
performSelectorOnMainThread:<(SEL)aSelector> withObject:<(id)arg> waitUntilDone:<(BOOL)wait>
Simple answer, you can not check the operation queue in the delegate method implementation. This method get called when only 1 of the operation queue get done, it will not be called by any other methods in your queue.
Check the queue where you initialized them.

Crash - "Collection <CALayerArray: 0x645dfc0> was mutated while being enumerated."

Goal is to "launch a spinner graphic at start of viewWillAppear that loads data before showing the tableview" so the user doesn't wonder why there's a delay before seeing the table. I.e. a UIActivityIndicatorView has been added to the window, and I just want to set the alpha to hide/show it.
I get this strange error when starting a thread to make sure the "spinning gears" imageview (tag=333) gets shown, before moving on to load/calculate stuff in viewWillAppear.
I don't get it on every call to [appdel addGearz] and [appdel removeGearz], it happens for both these, and it's random. It can happen after 2 viewWillAppears, or after 15. If I comment out the line that sets the alpha, everything works.
A typical viewWillAppear looks something like this,
[super viewWillappear];
self.title=#"Products listing"; //and other simple things
[appdel addGearz];
[self getProducts];
[self getThumbnails];
[myTableView reloadData]; //in case view already loaded and coming back from subview and data changed
And here is the code that crashes if the lines with .alpha are not commented out
-(void)addGearz {
[NSThread detachNewThreadSelector:#selector(gearzOn) toTarget:self withObject:nil];
}
-(void)removeGearz {
[NSThread detachNewThreadSelector:#selector(gearzOff) toTarget:self withObject:nil];
}
- (void)gearzOn {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[window viewWithTag:333].alpha=1.0;
//
// [[window viewWithTag:333] setNeedsDisplay];
[pool drain];
}
- (void) gearzOff {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[window viewWithTag:333].alpha=0.0;
//
// [[window viewWithTag:333] setNeedsDisplay];
[pool drain];
}
I've used someone else's code, so... anything obvious you can see? Surely I must be able to change alpha of UIViews in a thread? Do I need to "embed" the alpha-change in some "stop enumerating while I change this"-code?
I made it not crash by moving that alpha-change-line to above the pool alloc or below the [pool drain], but then I get a lot of "autoreleased with no pool in place - just leaking"-messages.
Apparently, there's something I don't understand about this thread code.
You must not try to modify the UI on a separate thread. UI should only be manipulated on the main thread.
Instead of detaching a new thread, you should use performSelectorOnMainThread:withObject:waitUntilDone:. This will ensure that the method will be called on the proper thread.

Why does popViewController only work every other time

I am totally stumped, here's the situation:
My app uses the Core Location framework to get the current location of the user and then pings my server at TrailBehind for interesting places nearby and displays them as a list. No problems.
To conserve batteries, I turn off the GPS service after I get my data from the server. If the user moves around while using the app and wants a new list he clicks "Refresh" on the navigation controller and the CLLocation service is again activated, a new batch of data is retrieved from the server and the table is redrawn.
While the app is grabbing data from my server I load a loading screen with a spinning globe that says "Loading, please wait" and I hide the navigation bar so they don't hit "back".
So, the initial data grab from the server goes flawlessly.
The FIRST time I hit refresh all the code executes to get a new location, ping the server again for a new list of data and updates the cells. However, instead of loading the table view as it should it restores the navigation controller bar for the table view but still shows my loading view in the main window. This is only true on the device, everything works totally fine in the simulator.
The SECOND time I hit refresh the function works normally.
The THIRD time I hit refresh it fails as above.
The FOURTH time I hit refresh it works normally.
The FIFTH time I hit refresh it fails as above.
etc etc, even refreshes succeed and odd refreshes fail. I stepped over all my code line by line and everything seems to be executing normally. I actually continued stepping over the core instructions and after a huge amount of clicking "step over" I found that the table view DOES actually display on the screen at some point in CFRunLoopRunSpecific, but I then clicked "continue" and my loading view took over the screen.
I am absolutely baffled. Please help!! Many thanks in advance for your insight.
Video of the strange behavior:
Relevant Code:
RootViewControllerMethods (This is the base view for this TableView project)
- (void)viewDidLoad {
//Start the Current Location controller as soon as the program starts. The Controller calls delegate methods
//that will update the list and refresh
[MyCLController sharedInstance].delegate = self;
[[MyCLController sharedInstance].locationManager startUpdatingLocation];
lv = [[LoadingViewController alloc] initWithNibName:#"Loading" bundle:nil];
[self.navigationController pushViewController:lv animated:YES];
[super viewDidLoad];
}
- (void)updateClicked {
//When the location is successfully updated the UpdateCells method will stop the CL manager from updating, so when we want to update the location
//all we have to do is start it up again. I hope.
[[MyCLController sharedInstance].locationManager startUpdatingLocation];
[self.navigationController pushViewController:lv animated:YES];
//LV is a class object which is of type UIViewController and contains my spinning globe/loading view.
}
-(void)updateCells {
//When the Core Location controller has updated its location it calls this metod. The method sends a request for a JSON dictionary
//to trailbehind and stores the response in the class variable jsonArray. reloadData is then called which causes the table to
//re-initialize the table with the new data in jsonArray and display it on the screen.
[[MyCLController sharedInstance].locationManager stopUpdatingLocation];
if(self.navigationController.visibleViewController != self) {
self.urlString = [NSString stringWithFormat:#"http://www.trailbehind.com/iphone/nodes/%#/%#/2/10",self.lat,self.lon];
NSURL *jsonURL = [NSURL URLWithString:self.urlString];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
NSLog(#"JsonData = %# \n", jsonURL);
self.jsonArray = [jsonData JSONValue];
[self.tableView reloadData];
[self.navigationController popToRootViewControllerAnimated:YES];
[jsonData release];
}
}
CLController Methods: Basically just sends all the data straight back to the RootViewController
// Called when the location is updated
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(#"New Location: %# \n", newLocation);
NSLog(#"Old Location: %# \n", oldLocation);
#synchronized(self) {
NSNumber *lat = [[[NSNumber alloc] init] autorelease];
NSNumber *lon = [[[NSNumber alloc] init] autorelease];
lat = [NSNumber numberWithFloat:newLocation.coordinate.latitude];
lon = [NSNumber numberWithFloat:newLocation.coordinate.longitude];
[self.delegate noteLat:lat];
[self.delegate noteLon:lon];
[self.delegate noteNewLocation:newLocation];
[self.delegate updateCells];
}
}
The first thought is that you may not want to send startUpdatingLocation to the CLLocationManager until after you've pushed your loading view. Often the first -locationManager:didUpdateToLocation:fromLocation: message will appear instantly with cached GPS data. This only matters if you're acting on every message and not filtering the GPS data as shown in your sample code here. However, this would not cause the situation you've described - it would cause the loading screen to get stuck.
I've experienced similarly weird behavior like this in a different situation where I was trying to pop to the root view controller when switching to a different tab and the call wasn't being made in the correct place. I believe the popToRootViewController was being called twice for me. My suspicion is that your loading view is either being pushed twice or popped twice.
I recommend implementing -viewWillAppear:, -viewDidAppear:, -viewWillDisappear: and -viewDidDisappear: with minimal logging in your LoadingViewController.
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"[%# viewWillAppear:%d]", [self class], animated);
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"[%# viewDidAppear:%d]", [self class], animated);
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
NSLog(#"[%# viewWillDisappear:%d]", [self class], animated);
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"[%# viewDidDisappear:%d]", [self class], animated);
[super viewDidDisappear:animated];
}
Then, run a test on your device to see if they are always being sent to your view controller and how often. You might add some logging to -updateClicked to reveal double-taps.
Another thought, while your #synchronized block is a good idea, it will only hold off other threads from executing those statements until the first thread exits the block. I suggest moving the -stopUpdatingLocation message to be the first statement inside that #synchronized block. That way, once you decide to act on some new GPS data you immediately tell CLLocationManager to stop sending new data.
Can you try and debug your application to see where the control goes when calling updateCells? Doesn't seem to be anything apparently wrong with the app.
Make sure that there are no memory warnings while you are in the LoadingViewController class. If there is a memory warning and your RootViewController's view is being released, then the viewDidLoad will be called again when you do a pop to RootViewController.
Keep breakpoints in viewDidLoad and updateCells. Are you sure you are not calling LoadingViewController anywhere else?
So, I never did get this to work. I observe this behavior on the device only every time I call popViewController programatically instead of allowing the default back button on the navigation controller to do the popping.
My workaround was to build a custom loading view, and flip the screen to that view every time there would be a delay due to accessing the internet. My method takes a boolean variable of yes or no - yes switches to the loading screen and no switches back to the normal view. Here's the code:
- (void)switchViewsToLoading:(BOOL)loading {
// Start the Animation Block
CGContextRef context = UIGraphicsGetCurrentContext();
[UIView beginAnimations:nil context:context];
[UIView setAnimationTransition: UIViewAnimationTransitionFlipFromLeft forView:self.tableView cache:YES];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:.75];
// Animations
if(loading) {
if (lv == nil) { lv = [[LoadingViewController alloc] initWithNibName:#"Loading" bundle:nil]; }
[self.view addSubview:lv.view];
[self.view sendSubviewToBack:self.tableView];
self.title = #"TrailBehind";
}
else {
[lv.view removeFromSuperview];
}
// Commit Animation Block
[UIView commitAnimations];
//It looks kind of dumb to animate the nav bar buttons, so set those here
if(loading) {
self.navigationItem.rightBarButtonItem = nil;
self.navigationItem.leftBarButtonItem = nil;
self.title = #"TrailBehind";
}
else {
UIBarButtonItem *feedback = [[UIBarButtonItem alloc] initWithTitle:#"Feedback" style:UIBarButtonItemStylePlain target:self action:#selector(feedbackClicked)];
self.navigationItem.rightBarButtonItem = feedback;
UIBarButtonItem *update = [[UIBarButtonItem alloc] initWithTitle:#"Move Me" style:UIBarButtonItemStylePlain target:self action:#selector(updateClicked)];
self.navigationItem.leftBarButtonItem = update;
[feedback release];
[update release];
}
}
Looking at your original code, I suspect this block very much:
- (void)viewDidLoad {
...
lv = [[LoadingViewController alloc] initWithNibName:#"Loading" bundle:nil];
[self.navigationController pushViewController:lv animated:YES];
[super viewDidLoad];
}
viewDidLoad is called every time the NIB is loaded, which can happen multiple times, especially if you run low on memory (something that seems likely given your remark that it only happens on device). I recommend that you implement -didReciveMemoryWarning, and after calling super, at the very least print a log so you can see whether it's happening to you.
The thing that bothers me about the code above is that you're almost certainly leaking lv, meaning that there may be an increasing number of LoadingViewControllers running around. You say it's a class variable. Do you really mean it's an instance variable? ivars should always use accessors (self.lv or [self lv] rather than lv). Do not directly assign to them; you will almost always do it wrong (as you are likely dong here).
I came across this while searching for the exact same issue, so while I'm sure you've already solved your problem by now, I figured I'd post my solution in case someone else runs across it...
This error seems to be caused when you assign two IBActions to the same UIButton in interface builder. It turned out that the button I used to push the view controller onto the stack was assigned to two IBActions, and each one was pushing a different controller onto the navigationController's stack (although you'll only end up seeing one of them - perhaps the last one to be called). So anyway, pressing the back button on the topmost view doesn't really dismiss it (or maybe it's dismissing the 2nd, unseen controller), and you have to press twice to get back.
Anyway, check your buttons and be sure they're only assigned to a single IBAction. That fixed it for me.