iPhone app delegates does not work properly - iphone

I am new to iPhone development. I am converting the date to the desired format and set it to the delegate and get its value in the another view. The session restarts when I tried to get the value from delegate. If I set the original date and not the formatted date in the set delegate, then I able to get the value in the another view. If I also give any static string value, then also I am able to the static string value back.
Only the formatted date which is string is set then the session restarts. If I print and check the value of the formatted date it prints the correct formatted date only. Here is my code for date conversion
NSString *dateval=[[stories objectAtIndex: storyIndex] objectForKey:#"date"];
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"EEE, MMM dd, yyyy"];
NSDate *inputDate = [inputFormatter dateFromString:dateval];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"MMMM dd"];
NSString *outputDate = [outputFormatter stringFromDate:inputDate];
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
[delegate setCurrentDates:outputDate];
Edit
This is displayed in console
inside view did load
[Session started at 2010-04-21 19:12:53 +0530.]
GNU gdb 6.3.50-20050815 (Apple version gdb-967) (Tue Jul 14 02:11:58 UTC 2009)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-apple-darwin".sharedlibrary apply-load-rules all
Attaching to process 4216.
(gdb)
In another view
- (void)viewDidLoad {
NSLog(#"inside view did load");
AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
NSString *titleValue=[delegate getCurrentDates];
self.navigationItem.title =titleValue ;
}
The get does not work properly. It works fine if I give any static string or the "dateval".

outputDate does not seems to be retained, so the value is lost at the end of the event loop (because of the NSAutoreleasePool).
You should retain the outputDate to avoid its release with something like that in the delegate:
- (void)setCurrentDates:(NSString *)value {
[value retain]; // <- Retain new value
[date release]; // <- Release old value;
date = value;
}
The best solution would be to have a declared property in the delegate with the retain attribute.

Related

Variable memory address attribution EXEC_BAD_ACESS

I have an allocated object where its attributes are store in the following memory places:
When I make a simple attribution of the NSDate attribute to a variable it gives me an EXEC_BAD_ACESS.
As you can see from the first image only the date attribute and the fileDate variable have different addresses.
Am I making some pointer related error?
The other 2 attributes are assigned correctly to the variables, it only happens with the NSDate so maybe I'm missing some detail about NSDate.
EDIT1
DownloadFile definition:
EDIT2
init function:
EDIT3
date parameter:
Is there any reason why you are not using ARC? There are quite a few memory management errors there causing leaks and one that should cause your crash.
NSDate *dateFromString = [dateFormatter dateFromString:receivedDate];
returns an autoreleased NSDate so when you then call the additional
[dateFromString autorelease];
you are overreleasing the NSDate hence your crash.
[pFile setDate:[[NSDate alloc] init]];
is a memory leak. Going through the setter setDate: will cause pFile to take a +1 retain on the date, which it should release in it's dealloc. The [[NSDate alloc] init] call returns a date object with +1 but is then never released elsewhere.
You can fix this either with
[NSDate date]
Or
[[[NSDate alloc] init] autorelease];
The first option is preferred

Potential leak of an object allocated on line …

I am getting contact details and am having memory problems in my shouldContinueAfterSelectingPerson method. I followed a tutorial and did this weeks ago but now when I click Product -> Analyze I get 'Potential leak of an object allocated on line' on these 3 lines:
[lastName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateOfBirth setText:birthday];
When clicking on these errors I get (though only number 2 for the third line):
Call to a function 'ABRecordCopyValue' returns a Core Foundation object with a + 1 retain count
Object leaked: allocated object is not referenced later in this execution path and has a retain count of + 1
The full code is shown below:
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
[firstName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty)];
[lastName setText:(__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMMM d, yyyy"];
birthday = [dateFormatter stringFromDate:(__bridge NSDate *)ABRecordCopyValue(person, kABPersonBirthdayProperty)];
[dateOfBirth setText:birthday];
Is there a fix around this and how important is it that I do fix it? I have one other potential leak of an object in my code.
A final note: I am using ARC.
You want this:
[lastName setText:(__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty)];
The reason you're seeing the warning from the analyser is that ABRecordCopyValue returns a CFStringRef with +1 retain count. You're then casting to an NSString* but saying to ARC not to take ownership of the object. That means it won't automatically add in the release for you. So you need to tell ARC to take ownership during the cast into Objective-C object land which is done using __bridge_transfer.
You could also have done:
CFStringRef string = ABRecordCopyValue(person, kABPersonLastNameProperty);
[lastName setText:(__bridge NSString *)string];
CFRelease(string);
Since the functions are returning new objects (they have copy in the name) you need to release those objects somehow.
This can be done by calling the appropriate method to release it, or by using __bridge_transfer instead of __bridge, which instructs ARC to take over the memory management and release it when needed.

returning a stringfromdate method

So here's some code that I'm having trouble with:
//format the date to a string for echoing it
NSDateFormatter* formattedDate = [[NSDateFormatter alloc] init];
[formattedDate setDateStyle:NSDateFormatterLongStyle]; //now myFormatted is set to a long style
NSString* dateForOutput = [formattedDate stringFromDate:self.datePickerOutlet.date];
//also now need to set the "you began on" text to the newly chosen date
[self.startDate setText:#"You started on: %#", dateForOutput];
The error that is given is: "Too Many Arguments to method call, expected 1, have 2"
I don't see why it's saying that I'm trying to pass in two methods.
I tried to do the following in case I was being stupid but it still gave me an error:
//format the date to a string for echoing it
NSDateFormatter* formattedDate = [[NSDateFormatter alloc] init];
[formattedDate setDateStyle:NSDateFormatterLongStyle]; //now myFormatted is set to a long style
NSString* dateForOutput = [formattedDate stringFromDate:self.datePickerOutlet.date];
//also now need to set the "you began on" text to the newly chosen date
NSString *foobar = #"You started on: %#", dateForOutput;
[self.startDate setText:foobar];
Error given: "Interface type cannot be statically allocated"
Frankly I have no idea why it's giving me this error... some help would be greatly appreciated.
It's probably just something small that I'm just not seeing for some reason =/
cheers,
Matt
Instead of the line
[self.startDate setText:#"You started on: %#", dateForOutput];
in the first block of code you have given, try the following line
[self.startDate setText:[NSString stringWithFormat:#"You started on: %#", dateForOutput]];
But it is better to go with the second statements,
NSString *foobar = [NSString stringWithFormat:#"You started on: %#", dateForOutput];
you are doing things in wrong way
You should do the Things in this way
NSDate* myDate=[NSDate new];
NSDateFormatter* formattedDate = [[NSDateFormatter alloc] init];
[formattedDate setDateStyle:NSDateFormatterLongStyle];
//now myFormatted is set to a long style
// here i just passed the current date
NSString* dateForOutput = [formattedDate stringFromDate:myDate];
//also now need to set the "you began on" text to the newly chosen date
NSString *foobar = #"You started on:";
//Now you can append The String
//this is the way you can append the string ..
foobar= [foobar stringByAppendingFormat:#"%#",dateForOutput];
[self.startDate setText:foobar];

NSMutableString access problem

So I'd like to access and display a formatted date outside my function. For the date format I am using NSDateFormatter which works fine..
My function (didFinishUpdatesSuccessfully) performs some action and if successful displays an UIAlertView which includes the formatted date. All that works fine..
- (void) didFinishUpdatesSuccessfully {
//--- Create formatted date
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd/MM/YYYY - hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:currDate]; // dateString contains the current date as a string
[dateFormatter release];
//--- UIAlertView
NSString *title = #"The update has been performed!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
message: dateString
delegate: nil
cancelButtonTitle: [FileUtils appResourceForKey:#"UPDATE_GENERAL_BUTTON_TITLE_OK"]
otherButtonTitles: nil];
[alert show];
[alert release];
//--- create new string
// NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString];
}
I now want to write the value of dateString into a global NSString or NSMutableString and access it somewhere else in the code, e.g. another function etc..
I thought about creating a NSMutableString like this:
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString]; and to access lastUpdated somewhere else, but ouside of this function lastUpdated is empty... Can you help? Cheers
NSMutableString* lastUpdated = [NSMutableString stringWithFormat:#"%#",dateString];
If you do that, you're declaring a local variable named lastUpdated. Even if there's another global variable with the same name, this local one will hide the global variable for as long as it's in scope (the life of your function).
To make this work, you need to declare a global lastUpdated somewhere outside of any function or method, probably near the top of a .m file:
NSMutableString *lastUpdated;
You can then access that variable from anywhere in the .m file. If you want to access it in other .m files, you'll want to add an extern declaration in the corresponding header (.h) file:
extern NSMutableString *lastUpdated;
With that declaration, you can use lastUpdated in any file that includes that header file.
Two things to know:
This is basic C stuff, so if it seems unfamiliar, you should review scope rules for C. Know the difference between a global variable, a static variable, a local variable, an instance variable (okay, plain old C doesn't have those), and a parameter.
Global variables are horrible. Don't trust anybody who tells you otherwise. I offer the advice above to help solve your immediate problem, but a better solution would be to figure out how to refactor your code so that you can avoid the need for a global variable. (And IMO a singleton isn't the answer, either. Singletons used just to access global data aren't much more than fancy-pants global variables.)
You should retain the string like.
NSMutableString* lastUpdated;
lastUpdated = [[NSMutableString stringWithFormat:#"%#",dateString] retain];
Now try to access in outside.

NSNumberFormatter leaks on NSCFNumber getObjectValue

I created a common method "isValidAmount" to check if the user inputs a correct amount in UITextField. This is working, but the problem is, I am getting leaks when the number is invalid. The leaked object is "NSCFNumber" and the responsible for that is "getObjectValue". I don't know what else to do. I already release the "formatter" below. I even tried to release "number" below. But still I keep on getting this leak. Please help.
+ (BOOL) isValidAmount:(NSString *)amount {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:amount];
[formatter release];
if (!number) {
return NO;
}
return YES;
}
By inspection, there is nothing wrong with that code.
Does it also leak on the device? Can you post the exact backtrace of the allocation that is leaked?