NSMutableString access problem - iphone

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.

Related

Custom Formatting of an NSNumber

in an ios application, I am trying to allow the user to enter a number and a format and I want to get a string with that number formatted as the user specified:
For that I have tried this:
- (NSString *)formatNumber:(NSNumber *)number withFormat:(NSString *)format
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setPositiveFormat:format];
NSString *formatedString = [formatter stringFromNumber:number];
return formatedString;
}
but if I try to call something like this:
NSNumber *number = [NSNumber numberWithDouble:1234567890];
NSString *string = [self formatNumber:number withFormat:#"###-###-####"];
I was expecting to get a result: 123-456-7890
But it is not working.
is the #"###-###-####" format wrong syntax ? or am I using the NSNumberFormatter wrong?
Thanks for any help
PS: I do not want to hard code an algorithm to loop through the characters and insert the dashes (-) because that format is just an example as the user is able to freely change it.
Thanks
EDIT
SORRY while writting my code here I missed a line. now added it
This may be useful:
https://discussions.apple.com/thread/2399192
Key quote:
Parentheses and dashes are not allowed in a number format.

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];

iphone passing value to label

I'm implementing a calendar as part of my app, it shows the selected date in nslog, but I need to send this value to a label,
it show the value as 2011-02-08 in nslog
I created a label in ib,(and connect to it)
in *ViewController.h
IBOutlet UILabel *dateis;
in *ViewController.m
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
[aTile flash];
dateis = [aTile date];
}
but I get the warning>
Incompatible Objective-C types assigning 'struct KLDate *', expected 'struct UILabel *'
EDIT, if I use
dateis.text = [aTile date];
I get the warning
incompatible Objective-C types 'struct KLDate *', expected 'struct NSString *' when passing argument 1 of 'setText:' from distinct Objective-C type
KLDate is the way the date was defined in the calendar,
so how can I pass this value to the label (working on nslog, view code call in *.m)
Thanks a lot!!
You can't just assign a "Date" to a "Label"...
You are obviously using Appcelerator framework. (KLDate type)
So what you are looking for is :
dateis.text = [NSString stringWithFormat:#"%#", aTile.date];
stringWithFormat: will in fact invoke descriptionmethod of KLDate, so you can also use the equivalent :
dateis.text = aTile.date.description;
To find this look at KLDate.h and check wich method returns a NSString * that you can assign to the good property of UILabel (look its documentation) which is text
You should check description method implementation if you need to write your own code to format the date...
try:
dateis.text = [aTile date];
Well, NSLog can take a lot of different class types as input and it figures out what it can display. What is a KLTile? How are you assigning the date to the KLTile, i.e. from what data structure to what data structure. Somewhere there's gotta be a NSString or a formatted NSDate. Maybe you can see the internal structure of a KLTile in the debugger.
ok, so I dont know if is the proper thing to do, but its working!!
(please enlighten me to know if is fine!)
I just figured that if label wanted a string, then I will give it a string, haha, so,
- (void)calendarView:(KLCalendarView *)calendarView tappedTile:(KLTile *)aTile{
NSLog(#"Date Selected is %#",[aTile date]);
[aTile flash];
NSString *str =[NSString stringWithFormat:#"%#", [aTile date]];
dateis.text = str;
}