problem in Error handling method in iPhone sdk - iphone

I am using Error Handling Method globally in appDelegate method to caught exceptions.
Code:
//In appDelegate.m
static void uncaughtExceptionHandler(NSException *exception)
{
printf("\n ===== In uncaughtExceptionHandler Method =======");
NSArray *stack = [exception callStackReturnAddresses];
NSLog(#"======== Exception *************%#", stack);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"" message:#"Exception Occured"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
{
// Override point for customization after application launch.
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
}
I am implementing an Alert in the uncaughtExceptionHandler Method. But I am getting Error as
"self " undeclared.
Can Anyone Please Suggest how to implement Alert when the uncaughtExceptionHandler is
called.
thanks in Advance.

Try implementing this Handle Uncaught Exception

self is undefined within a C function. If you want to make the application delegate the delegate for your alert view then you should probably replace self with [[UIApplication sharedApplication] delegate].

Related

EXC_BAD_ACCESS code 2 on UIAlertView in iOS6

I'm trying to figure out why im getting this crash in my app.
It works perfectly fine in Xcode 4.4 running in the simulator with ios5.1, but when i switch into xcode 4.5 and ios6 I'm getting an EXC_BAD_ACCESS code 2. Here is my code:
- (void) myMethod
{
UIAlertView *alertview = [[[UIAlertView alloc]initWithTitle:#"Title" message:#"message" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] autorelease];
alertview.tag = 1
[alertview show];
}
this is giving me an EXC_BAD_ACCESS code 2 on the [UIAlertView show] line
any ideas?
thanks!
I've got it.
I have the same problem, in my case it seems that the method is thrown from background now (now in ios7, in ios6 UIAlertView was automatically put into the main-thread as #nodepond says -thanks!-)..
try to assure that the method is shown from main thread:
[alertView performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
Good luck!
It's happened with me, even in 2014.
The problem is want to use an object already released.
What I did wrong:
//class B with UIAletViewDelegate
-(void) showAlert{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle bla bla...];
[alert show];
}
//class A
viewDidLoad{
MyClassB *B = [[B alloc] init];
[B showAlert];
}
What is the right way:
//Class A
#implementation A{
ClassB *B;
}
viewDidLoad{
B = [[B alloc] init];
[B showAlert];
}

how to pass a Parameter from a Method which opens a UIAlertView to the UIAlertViewDelegate-Method?

Given the following code:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
if (mainViewController.loggedIn) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"test" message:#"notification received. view now?" delegate:self cancelButtonTitle:#"Later" otherButtonTitles: #"Show"), nil];
NSString *hash = [userInfo objectForKey:#"id"];
[alert setValue:hash forKey:#"hash"];
[alert show];
[alert release];
}
}
Here I try to set a value (hash) for the key #"hash". I'm doing this, because I need this hash value in case the user presses the "Show" button. Then - in the delegate method - I try to read the value again:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *hash = [alertView valueForKey:#"hash"];
if (hash != nil) {
// send hash to server to show the correct site
}
}
}
But as soon as i call[alert setValue:hash forKey:#"hash"]; my iphone app crashes.
This is what i see in the console:
* Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key hash.'
Does anybody has an idea what I made wrong. Or how could i pass my "hash" value to the clickedButtonAtIndex method?
Declare hash as NSString class member. While you are showing the alertview, set the hash variable. Also, set a tag to the alertview.
In clickedButtonAtIndex method, check the alertview tag and use the hash value if required.

Am I releasing memory correctly?

I have the following helper object:
LikeHelper* likeHelper = [[LikeHelper alloc]init];
likeHelper.delegate = self;
[likeHelper performLike:self.messageID];
[likeHelper release];likeHelper=nil;
performLike will do some NSURLConnection stuff and then tell the delegate whether or not it was successful.
#pragma mark LikeHelperDelegate Methods
-(void)performLikeFinished:(BOOL)isSuccessful{
if (isSuccessful) {
UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"The message has been liked" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else {
UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"There was a problem liking your message" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
Am I releasing the likeHelper in the right place?
If the performLike: method is asynchronous, the likeHelper will propably be released before the performLikeFinished: method is called. You should release the likeHelper in the dealloc: method of the owner object or in the performLikeFinished: implementation in the LikeHelperDelegate to prevent releasing it too soon but if you do that, be aware of JeremyPs comment below!.
If the performLike: method is synchronous, you are doing the right thing but you wouldn't need the delegate to collect the result.
Yes you are, your code is according to the guidelines.
If your code do not work then the problem might be that LikeHelper need to retain self from within -[LikeHelper performLike:].
You should also not retain the LikeHelperDelegate, that might be another cause of confusion or errors.

Is it me or xcode... Somethings wrong with my braces and it just causes errors! Please help! iPhone SDK + Urban Push

Help!
I cant find whats wrong. My code is up and mostly running and i needed to incorporate Urban Air push notification and there is something wrong with my code. If there is a better or different way to incorporate this that works without my errors I would appreciate that.
I took this code from a tut of Urban Airmail. I wasnt sure what to inlude and what not to from the sample app.
Now for my code. Ill notate where I get errors They are stray / errors and expected ; b4 :
errors
If you could fix the code that would be awesome!
//
// SuperSlickAppDelegate.m
// SuperSlick
//
// Created by on 8/2/10.
// Copyright __MyCompanyName__ 2010. All rights reserved.
//
#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
#import "SuperSlickAppDelegate.h"
#import "SuperSlickViewController.h"
#import "Reachability.h"
#implementation SuperSlickAppDelegate
#synthesize window;
#synthesize viewController;
#pragma mark -
#pragma mark Application lifecycle
#define kApplicationKey #"rnftzaemRp2HJMsNjwZvGQ"
#define kApplicationSecret #"X1XdTjdWQIaL72e-gXew5A"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
Reachability *r = [Reachability reachabilityWithHostName:#"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"You require an internet connection via WiFi or cellular network to use this! Try the settings app for WiFi Connectivity." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
//Register for notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
//ERROR HERE in line above Stray 357
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
//ERROR HERE Wrong type argument to unary minus + stray
// Get a hex string from the device token with no spaces or < >
self.deviceToken = [[[[_deviceToken description] stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"Device Token: %#", self.deviceToken);
if ([application enabledRemoteNotificationTypes] == 0) {
NSLog(#"Notifications are disabled for this application. Not registering with Urban Airship");
return;
}
// this is straight out of the UA sample code
NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease];
NSString *UAServer = #"https://go.urbanairship.com";
NSString *urlString = [NSString stringWithFormat:#"%#%#%#/", UAServer, #"/api/device_tokens/", self.deviceToken];
NSURL *url = [NSURL URLWithString: urlString];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
request.requestMethod = #"PUT";
// Authenticate to the server
request.username = kApplicationKey;
request.password = kApplicationSecret;
[request setDelegate:self];
[request setDidFinishSelector: #selector(registrationSuccessMethod:)]; // if you want to do something with the token
[request setDidFailSelector: #selector(requestWentWrong:)];
[queue addOperation:request];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
NSLog(#"Failed to register with error: %#", error);
}
- (void)requestWentWrong: (ASIHTTPRequest *)request {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSError *_error = [request error];
NSLog(#"ERROR: NSError query result: %#", _error);
UIAlertView *someError = [[UIAlertView alloc] initWithTitle:
#"Network error" message: NSLocalizedString( #"Error registering with notifiction server",
#"Error registering with notifiction server")
delegate: self
cancelButtonTitle: #"OK"
otherButtonTitles: nil];
[someError show];
[someError release];
}
// Add the view controller's view to the window and display.
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
}
- (void)applicationWillResignActive:(UIApplication *)application {
/*
Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
*/
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
/*
Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
*/
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
/*
Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
*/
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
/*
Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
*/
}
- (void)applicationWillTerminate:(UIApplication *)application {
/*
Called when the application is about to terminate.
See also applicationDidEnterBackground:.
*/
}
#pragma mark -
#pragma mark Memory management
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
/*
Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
*/
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
New Code that has troubles:
//Register for notifications
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
;}}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
//ERROR HERE Wrong type argument to unary minus and semi colon b4
Doesn't look like you ever ended your application:didFinishLaunchingWithOptions: method - you should have an end brace after this line:
[[UIApplication sharedApplication] registerForRemoteNotificationTypes...
So it should look like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)];
//ERROR HERE in line above Stray 357
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken {
...
}
That should do it.
For your second code block - without seeing the surrounding code it's difficult to see what you're trying to do...you likely shouldn't have:
;}}
It should probably just be:
}
If you are looking for unbalanced parentheses, then this is probably the part that is giving you troubles:
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
}

handleOpenURL not called using a custom url schema in iPhone OS

I have successfuly added my own url schemes to my App. The App correctly launches using the schemes.
Now I want to handle the incoming data but the delegate is not called. It is an universal app and I have added the following function to both AppDelegates:
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
if (!url) { return NO; }
NSString *URLString = [url absoluteString];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"test message", nil)
message:URLString
delegate:self
cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
return YES;
}
I am testing with a schema like: myapp://appalarm.com
…and would expect to be appalarm.com in the URLString
What is wrong with it?
Thanks for your responses!
I tried to clarify in another post. The answer of Ashley Clark is only partly correct. Under OS 4.0 the handleOpenURL gets called (at least for file URLs) and you have to implement it to handle open url calls for when the app is in background. Thus, opening the file in both methods may open it twice (if applicationDidFinishLaunchingWithOptions returned YES, which it should). See another post.
If your application delegate has implemented 'applicationDidFinishLaunchingWithOptions:' then the 'handleOpenURL:' method will never be called. Look at the options passed in through the other method to determine how your app was launched and what behavior you should implement.
Try your code into below function
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
if (!url) { return NO; }
NSString *URLString = [url absoluteString];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"test message", nil)
message:URLString
delegate:self
cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alert show];
[alert release];
return YES;
}