returning a stringfromdate method - iphone

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

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.

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.

How to get an NSDate from an integer passed in as and id?

This is driving me nuts so I hope someone can help an Objective-C noob figure this out. Here's the deal:
I'm developing an iPhone app using Titanium Appcelerator and I'm trying to create an add-on module in XCode that will allow me to send an event to the iPhone calendar. What I'd like to do is to calculate the date and time in terms of seconds since Jan 1, 2001 (GMT) and send it directly to calendar without having to mess with the string-to-date stuff that seems always to return the wrong time. To this point, I've not been able to get the integer into the event date fields, both of which are NSDate types.
Titanium takes arguments from Javascript and compiles it into object code, so I can call my "cal" object like this:
var startDate = 316367923;
var endDate = 316367923;
var results = cal.newEvent(startTime,endTime)
. . . and this is how the "cal" object receives that call:
-(BOOL)newEvent:(id)args {
id startDate = [args objectAtIndex:0];
id endDate = [args objectAtIndex:1];
...
What I'm hoping to do get these integers into the event object:
EKEventStore *eventDB = [[EKEventStore alloc] init];
EKEvent *theEvent = [EKEvent eventWithEventStore:eventDB];
...
theEvent.startDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) startDate];
theEvent.endDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) endDate];
This compiles with no errors but causes my app to bomb nonetheless, so I'm figuring I've got something missing in my understanding. Any idea of where I'm going wrong?
Thanks,
Mark
Quite probably 'args' is an NSArray, hence startDate and endDate are objects, not literals. You probably want to do something like:
theEvent.startDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:[startDate intValue]];
If e.g. startDate is an NSNumber. Otherwise, check out the Titanium docs to find out the type of numbers passed in.
This may not be the cause of your crash, but the initWithTimeIntervalSinceReferenceDate NSDate method is expecting an NSTimeInterval (defined as typedef double NSTimeInterval) not an integer.
i.e.: Its method signature is:
- (id)initWithTimeIntervalSinceReferenceDate:(NSTimeInterval)seconds
I'd bet startDate and endDate are being converted to NSNumber objects instead of ints. Therefore, try the following lines:
theEvent.startDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) [startDate intValue]];
theEvent.endDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) [endDate intValue]];
I doubt that your crash has anything to do with it but, you might be leaking. The lines:
theEvent.startDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) startDate];
theEvent.endDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate: (int) endDate];
assign an object with retain count 1, if the setter for startDate and EndDate takes ownership of them (I don't know if java will do that or not so I might be wrong) you must store them in a local variable before assigning them to theEvent, so that you can call release afterwards.
so it would look like this:
NSDate *sDate = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:[startDate intValue]];
theEvent.startDate = sDate;
[sDate release];

DatePicker stopping CoreData working as expected

I have an app which saves text and the date from a UIDatePicker and then shows that note if you got back into that date in the UIDatePicker.
It works great! Only I have found that setting the UIDatePicker date to today stops CoreData working.
It's only when I run this setDate line does it stop core data from working. The app runs fine without crashing, it just doesn't save any data. If I comment that line out, it works a charm. But I need to have the UIDatePicker on today when the app loads.
I use this when the application starts:
NSDate *now = [[NSDate alloc] init];
[datePicker setDate:now];
This to fetch the note:
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *testEntity = [NSEntityDescription entityForName:#"DatedText" inManagedObjectContext:self.managedObjectContext];
[fetch setEntity:testEntity];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"dateSaved == %#", datePicker.date];
[fetch setPredicate:pred];
NSError *fetchError = nil;
NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
if (fetchError != nil) {
NSLog(#"fetchError = %#, details = %#",fetchError,fetchError.userInfo);
}
noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:#"savedText"];
And this to save the note:
NSManagedObject *newDatedText;
newDatedText = [NSEntityDescription insertNewObjectForEntityForName:#"DatedText" inManagedObjectContext:self.managedObjectContext];
[newDatedText setValue:noteTextView.text forKey:#"savedText"];
[newDatedText setValue:datePicker.date forKey:#"dateSaved"];
NSError *saveError = nil;
[self.managedObjectContext save:&saveError];
if (saveError != nil) {
NSLog(#"[%# saveContext] Error saving context: Error = %#, details = %#",[self class], saveError,saveError.userInfo);
}
Remember NSDate saves not only DD/MM/YYYY but also HH:MM:SS.
At a guess I think when you pick a DD/MM/YYYY from the picker, it saves with a default time of 0:00:00 but in the case above when you set the picker date to now you are actually manipulating the HH:MM:SS to something else (even though you don't see it manually).
To illustrate what I'm trying to say, when you fetch is with a predicate of (dateSaved == picker.date) it is looking for a date in the format DD/MM/YYYY 00:00:00 and for arguments sake you may have saved it on DD/MM/YYYY 09:00:01.
You will need to do some formatting of your NSDate attribute if you want this to work.
Datepicker is by default set to todays date only. You don't need to do it manually.

iPhone app delegates does not work properly

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.