iPhone: Using Alerts to Help Debugging - iphone

I've been building a rather complex system and there's come the time now where I want more concise debugging. I would like to display the contents of a variable (for this example an NSString called v_string) in a notification window (the kind of window that appear when you receive an SMS text).
Is there an easy way to just call an alert with a variable?
Thanks in Advance,
Dan

NSLog does not do? If not (like if you need to debug an application running on a disconnected device), you can extend the UIAlertView with a category:
#implementation UIAlertView (Logging)
+ (void) log: (id <NSObject>) anObject
{
NSString *message = [anObject description];
UIAlertView *alert = [[self alloc] initWith…];
[alert show];
[alert release];
}
And then in code:
NSString *anInterestingString = …;
[UIAlertView log:anInterestingString];

When you build the string to display in the alert window, simply append your variable's string represenation using stringByAppendingString.

Alert window is cumbersome. Use NSLog instead:
NSLog(#"Variable is: %#", v_string);
And in Xcode's console you will see that text.

UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"My Debug String" message:v_string delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[message show];
[message release];
I think this way you can see what you want.
But, as zoul said, why not to use NSLog(#"my var: %#", v_string); ?
Hope that it helps.

Related

Can't figure out an error with stringWithFormat

I'm having a really basic problem with NSString stringWithFormat. I want to take the name that the user enters and display in an alertView: Welcome username.
NSString *welcomeMessage = [NSString stringWithFormat:(#"Welcome %#", passedData)];
UIAlertView *alert = [[UIAlertView alloc] //show alert box with option to play or exit
initWithTitle: welcomeMessage
message:#"Once you press \"Play\" the timer will start. Good luck!"
delegate:self
cancelButtonTitle:#"I want out!"
otherButtonTitles:#"Play",nil];
[alert show];
passedData is the username that has been entered. The way I have it at the moment - only the username is being displayed in the title of the alert box, and not the "Welcome" part. I know i'm missing some really basic knowledge here but would appreciate some help.
I think that () are not needed. Try using that:
NSString *welcomeMessage = [NSString stringWithFormat:#"Welcome %#", passedData];
instead of
NSString *welcomeMessage = [NSString stringWithFormat:(#"Welcome %#", passedData)];
Hope it helps

Expected Expression before ":" token

I am getting this error in first two lines of code given below
and the error is "Expected Expression before ":" token"....
some one please help me to overwrite this....
(IBAction)buttonPressed {
NSInteger stateRow =[picker selectedRowInComponent:kStateComponent];
NSInteger zipRow = [picker selectedRowInComponent:kZipComponent];
NSString *state=[self.states objectAtIndex:stateRow];
NSString *zip=[self.zips objectAtIndex:zipRow]
NSString *title=[[NSString alloc]initWithFormat:#"You selected zip code %#",zip];
NSString *message=[[NSString alloc]initWithFormat:#"%# is in %#",zip,state];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[title release];
[message release];
}
You have to write it as
(IBAction)buttonPressed {
Infact it should be
-(IBAction)buttonPressed {
May be - is missing that might be creating this error.
Hope this helps.
EDIT:
If still it doesnt help, then you may try this.
-(IBAction)buttonPressed:(id)sender {
EDIT-2:
Also you are missing a ; at the end of statement no 4
that is
NSString *zip=[self.zips objectAtIndex:zipRow]
You should add a semicolon(;) there at the end
Hope this solves it
There's a - missing right at the beginning before (IBACTION).
I have tested this code and its working properly.
change the "(NSInteger)component" as per requirement of picker.
- (IBAction) buttonPressed:(id)sender {
NSInteger stateRow =[pickerView selectedRowInComponent:"(NSInteger)component"];
NSInteger zipRow = [pickerView selectedRowInComponent:"(NSInteger)component"];
NSLog(#"stateRow - %d",stateRow);
NSLog(#"zipRow - %d",zipRow);
}
And also put - (IBAction) buttonPressed:(id)sender; in .h file

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.

UIAlertView Pops Up Three Times per Call Instead of Just Once

I am getting odd behavior from an NSAlert in two different parts of my program. The behavior is:
Alert appears and then spontaneously disappears.
Alert reappears and then remains until dismissed by user i.e. normal behavior.
Alert reappears again.
This behavior only occurs the first time the method that displays the alert is called. After that first time, it behaves normally.
Here is the code for the one of the parts in which the behavior occurs:
UIAlertView * locationAlert = [[UIAlertView alloc] initWithTitle:#"You are in the right place." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[locationAlert show];
[locationAlert release];
Or if you prefer, with a bit more context:
- (IBAction)locateMe {
NSLog(#"About to check location");
locMan = [[CLLocationManager alloc] init];
locMan.delegate = self;
locMan.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locMan.distanceFilter = 1609; //1 mile
[locMan startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation * )oldLocation {
if (newLocation.horizontalAccuracy >= 0) {
CLLocation *airportLocation = [[[CLLocation alloc] initWithLatitude:51.500148 longitude:-0.204669] autorelease];
CLLocationDistance delta = [airportLocation getDistanceFrom: newLocation];
long miles = (delta * 0.000621371) + 0.5; //metres to rounded mile
if (miles < 3) {
UIAlertView * locationAlert = [[UIAlertView alloc] initWithTitle:#"You are in the right place." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[locationAlert show];
[locationAlert release];
[locMan stopUpdatingLocation];
} else {
UIAlertView * locationAlert = [[UIAlertView alloc] initWithTitle:#"You are not in the right place." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[locationAlert show];
[locationAlert release];
[locMan stopUpdatingLocation];
}
}
}
- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
UIAlertView * locationAlert = [[UIAlertView alloc] initWithTitle:#"Error." message:error.code delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[locationAlert show];
[locMan release];
locMan = nil;
}
Any ideas? Thanks.
Edit---------
The other place this happens is:
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
NSString * errorString = [NSString stringWithFormat:#"Unable to download feed from web site (Error code %i )", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
For context the first case is in the AppDelegate and the second in the view controller for the 1st tab view. The second problem occurs every time the xml is reloaded when there is no internet connection. The first one only occurs the first time the function is called.
Edit-----
If I move the alert it works. Unfortunatly this is not where I want it!
- (IBAction)locateMe {
UIAlertView * locationAlert = [[UIAlertView alloc] initWithTitle:#"You are in the right place." message:nil delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[locationAlert show];
/*
NSLog(#"About to check location");
locMan = [[CLLocationManager alloc] init];
locMan.delegate = self;
locMan.desiredAccuracy = kCLLocationAccuracyThreeKilometers;
locMan.distanceFilter = 1609; //1 mile
[locMan startUpdatingLocation];*/
}
Update:
I set some NSLog entries and discovered that despite the addition of [locMan stopUpdatingLocation] the didUpdateToLocation function was running multiple times.
I guess the spontaneous disappearance happens because the alert view is called again and the programme clears the first instance to make way for the second automatically.
Any ideas as to why [locMan stopUpdatingLocation] doesn't work would be appreciated but in the mean time I just moved the declaration of the locationAlert out of the function (so it is global), set it in the initial locate me function and use the following the first time it is called:
[locationAlert show];
locationAlert = nil;
That way it works perfectly.
You're not turning off your location manager when you first show the alert. As the location is refined by the device (ie, the accuracy is increased), your callback will be (potentially) called multiple times. You should use [locMan stopUpdatingLocation] after your alert display.
I set some NSLog entries and discovered that despite the addition of [locMan stopUpdatingLocation] the didUpdateToLocation function was running multiple times.
I guess the spontaneous disappearance happens because the alert view is called again and the programme clears the first instance to make way for the second automatically.
Any ideas as to why [locMan stopUpdatingLocation] doesn't work would be appreciated but in the mean time I just moved the declaration of the locationAlert out of the function (so it is global), set it in the initial locate me function and use the following the first time it is called:
[locationAlert show];
locationAlert = nil;
That way it works perfectly.
I think the NSAlert disappearing on its own is the key to solving this.
It's simple to explain why an alert displays unexpectedly i.e. it's just been called unexpectedly. However, it's not so common to programmatically dismiss an alert. Whatever is causing it to disappear is most likely triggering the display again.
To debug I suggest:
(1) Looking in your code for the NSAlert – dismissWithClickedButtonIndex:animated: method and see if somehow you're actually dismissing the alert programmatically.
(2) I believe (someone double-check me on this) that an alert view is added as a subview to whichever base view is currently on screen. It might be that the base view is disappearing for some reason and taking the alert view with it. If the view disappears and then reappears rapidly enough, it might not be obvious when the alert is frontmost. (Edit: see Ed Marty's comment below.)
(3) Since this happens in two separate pieces of the app, compare both to find a common element or structure. That common element might be the cause.
An odd problem.
Edit01: Updated for additional info
If locMan isan instance variable, it should be defined as a property and you should access it every time withself.locMan By accessing it directly, you lose your automatic retention management.
I encountered the same exact issue with the alert dialog appearing momentarily, reappearing, and finally appearing again after being dismissed. I was making a string comparison before deciding to show the alert view:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if([string isEqualToString:#"OK"]) {
NSLog(#"(Settings)Registration Successful");
statusField.text = #"Registration successful!";
[settingsActivity stopAnimating];
}
else {
NSLog(#"(Settings)Registration Failure");
[settingsActivity stopAnimating];
UIAlertView * regFail = [[[UIAlertView alloc] initWithTitle:#"Registration Error!" message:#"Please check your email address and try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] autorelease];
[regFail show];
}}
To correct this behavior I simply verified the returned string rather than just showing the alert:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if([string isEqualToString:#"OK"]) {
NSLog(#"(Settings)Registration Successful");
statusField.text = #"Registration successful!";
[settingsActivity stopAnimating];
}
else if([string isEqualToString:#"Error"]) {
NSLog(#"(Settings)Registration Failure");
[settingsActivity stopAnimating];
UIAlertView * regFail = [[[UIAlertView alloc] initWithTitle:#"Registration Error!" message:#"Please check your email address and try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil] autorelease];
[regFail show];
}
I also got the Same problem while working on Location Manager. Here i checked with Nslog but it is executing multiple times, finally i fount that i am creating multiple objects and using Sharedinstance for same ViewController that contains Location Manger but i am not releasing the object, so at perticular location how many objects if we create that many times the location detects.So while working on LocationManger check handling objects thoroughly to reduce these type of problems.

UIAlertView Messages

Trying to include a instance variable in a message that a UIAlertView Shows.
lostAlert = [[UIAlertView alloc] initWithTitle:#"Sorry" message:(#"You Were Wrong, the correct structure was %#", structureName) delegate:self cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
however, when the Alert is shown, no message is shown.
Any ideas and help would be appreciated :)
Sam
did you try it with:
[NSString stringWithFormat:#"You Were Wrong, the correct structure was %#", structureName]
instead of
(#"You Were Wrong, the correct structure was %#", structureName)