Getting Error with pushing view on NavBar - iphone

When I push a view, I am getting the following errors in the console:
nested push animation can result in corrupted navigation bar
Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted.
Any ideas how to fix this?
This is the method that pushes the new veiw:
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString * dateString = [formatter stringFromDate:d];
if ( [data containsObject:dateString] )
{
NSDate * searchDate = [formatter dateFromString:dateString];
NSCalendar * calendar1 = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar1 dateByAddingComponents:dateComponents toDate:searchDate options:0];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
[request setPredicate: predicate1];
[request setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"xxx array: %#", array);
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
self.selectedSession = (Session *)[array objectAtIndex:0];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
sessionViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
[sortDescriptor release];
[request release];
[sortDescriptors release];
}
}

Related

How to compare an array of NSStrings containing Dates in ascending order

I have an Array in which contains a list of dates represented as strings:
NSMutableArray *objArray=[[NSMutableArray alloc]init];
[objArray addObject:#"18-01-2013 2:51"];
[objArray addObject:#"16-01-2013 5:31"];
[objArray addObject:#"15-01-2013 3:51"];
[objArray addObject:#"17-01-2013 4:41"];
[objArray addObject:#"03-02-2013 3:21"];
[objArray addObject:#"05-01-2013 3:01"];
please tell me how to arrange this array in ascending order by using dates.
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd-MM-yyyy hh:mm"];
NSComparator compareDates = ^(id string1, id string2)
{
NSDate *date1 = [formatter dateFromString:string1];
NSDate *date2 = [formatter dateFromString:string2];
return [date1 compare:date2];
};
NSSortDescriptor * sortDesc = [[[NSSortDescriptor alloc] initWithKey:#"self" ascending:NO comparator:compareDates]autorelease];
[objArray sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
By using this code i got exact output, thank you for all
we can do another way to get sorting array with dates
NSArray *objArr = [[NSArray alloc]initWithObjects:#"2003/08/02 03:00 ",#"2001/02/04 04:00 ",#"2001/02/04 05:00 ",#"2010/05/01 08:00 ",#"2002/12/02 02:00 ",#"2012/11/05 02:00 ",#"2013/10/01 12:00 ", nil];
NSArray *sortedArray = [objArr sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [(NSDate * )firstObject compare: (NSDate * ) secondObject];
}];
NSLog(#"sorteed Array %#",sortedArray);
NSSortDescriptor * descLastname = [[NSSortDescriptor alloc] initWithKey:#"active" ascending:YES];
[livevideoparsingarray sortUsingDescriptors:[NSArray arrayWithObjects:descLastname, nil]];
[descLastname release];
videoparsing = [livevideoparsingarray copy];
livevideoparsingarray is my array which I have sort & active is my tag which is in array which I have sort. You change with your requirements.
You can do this by using NSSortDescriptor
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: YES];
return [objArray sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *str1 = #"18-01-2013";
NSString *str2 = #"16-01-2013";
NSString *str3 = #"15-01-2013";
NSString *str4 = #"17-01-2013";
NSString *str5 = #"03-02-2013";
NSString *str5 = #"05-01-2013";
NSArray *arr = [NSArray arrayWithObjects:str1, str2, str3,str4,str5 nil];
arr = [arr sortedArrayUsingFunction:dateSort context:nil];
NSLog(#"New dates %#",arr);
}
//The date sort function
NSComparisonResult dateSort(NSString *s1, NSString *s2, void *context) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *d1 = [formatter dateFromString:s1];
NSDate *d2 = [formatter dateFromString:s2];
return [d1 compare:d2]; // ascending order
// return [d2 compare:d1]; // descending order
}
Try this
NSMutableArray *objArray;
objArray=[[NSMutableArray alloc] init];
[objArray addObject:#"18-01-2013 2:51"];
[objArray addObject:#"16-01-2013 5:31"];
[objArray addObject:#"15-01-2013 3:51"];
[objArray addObject:#"17-01-2013 4:41"];
[objArray addObject:#"03-02-2013 3:21"];
[objArray addObject:#"05-01-2013 3:01"];
NSSortDescriptor *sort_Date=[[NSSortDescriptor alloc] initWithKey:#"self"ascending:NO];
NSLog(#"%#",[[objArray sortedArrayUsingDescriptors:#[sort_Date]] description]);
I got below response
2013-02-06 11:23:35.100[1135:c07]
(
"18-01-2013 2:51",
"17-01-2013 4:41",
"16-01-2013 5:31",
"15-01-2013 3:51",
"05-01-2013 3:01",
"03-02-2013 3:21"
)

How to update and remove calendar event?

I am doing a sample application using iPhone calendar events. I am able to save the calendar event from my application to iPhone native calendar. While saving I am saving the saved event identifier in to my application database. Now I need to update the same event or remove the event. How can I do using the event Identifier which is saved in my database. Here is the piece of code for saving the event and saving the event identifier into database.
ENTITYCMAPPIPHONE *appointmentCM;
NSError *error;
NSFetchRequest *fetchRequest =
[managedObjectModel fetchRequestFromTemplateWithName:#"FetchForIphoneAppointment" substitutionVariables:nil];
NSArray *fetchedObjects= [context executeFetchRequest:fetchRequest error:nil];
int fetchCount = [fetchedObjects count];
if ([fetchedObjects count]>0) {
for (appointmentCM in fetchedObjects) {
NSLog(#"Appoint subject %#", appointmentCM.subject);
NSLog(#"APP notes %#", appointmentCM.notes);
appoint_ID = [appointmentCM.mobAppID intValue];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2012-09-10 13:55:15"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
NSInteger day = [components day];
NSDateFormatter *weekDay = [[[NSDateFormatter alloc] init] autorelease];
[weekDay setDateFormat:#"EEE"];
NSDateFormatter *calMonth = [[[NSDateFormatter alloc] init] autorelease];
[calMonth setDateFormat:#"MMMM"];
EKEventStore *eventStore1 = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore1];
event.title = appointmentCM.subject;
event.notes = appointmentCM.notes;
event.startDate = date;
event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
[event setCalendar:[eventStore1 defaultCalendarForNewEvents]];
NSError *err;
[eventStore1 saveEvent:event span:EKSpanThisEvent error:&err];
eventID = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[self updateIphoneCalendarEventID];
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
}
-(void)updateIphoneCalendarEventID{
NSError *error;
NSDictionary *subs;
subs = [NSDictionary
dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:appoint_ID], #"search_appID", nil];
NSFetchRequest *fetchRequestCheckNil =
[managedObjectModel fetchRequestFromTemplateWithName:
#"FetchEditIphoneCalendar" substitutionVariables:subs];
NSArray *fetchedObjects=[context executeFetchRequest:fetchRequestCheckNil error:nil];
if ([fetchedObjects count]>0) {
for (ENTITYAPPOINTMENTS *appDetails
in fetchedObjects) {
[self updateDBModelForAppointments:appDetails];
}
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
-(void)updateDBModelForAppointments:(ENTITYAPPOINTMENTS *)contactDetails{
contactDetails.iphoneAppID = eventID;
}
EKEventStore *eventStore = [[[EKEventStore alloc] init] autorelease];
NSString *idenfier = nil;//.....;// Get identifier stored in your application database
NSError *err = nil;
EKEvent *ev = [eventStore eventWithIdentifier:idenfier];
if(err){
NSLog(#"Error: %#",[err localizedDescription]);
}
else
{
// manipulate event...
ev.title = #"new title";
ev.location = #"new location";
// or remove:
[eventStore removeEvent:ev span:EKSpanFutureEvents commit:NO error:&err];
}

How to use NSPredicate for fetching property having NSDate type?

I have a column in core data that stores a date (eg:2006-01-26). I used an array to store all the years by using NSDateComponents on these stored dates.(e.g.: on above date if i use NSDateComponents, I get 2006 as a year). These years are NSNumbers, and using them in my predicate I want to fetch the column which is NSDate with all Date components. And fetched records should be only of particular year. I am now confused about how I could match a year components with one of those in array, and create predicate.
- (void)viewDidLoad
{
[super viewDidLoad];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSError *error;
//AppDelegate *app = [[UIApplication sharedApplication]delegate];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Movies" inManagedObjectContext:self.managedObjectContxt];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:#"releaseDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,nil];
[request setSortDescriptors:sortDescriptors];
//[request setReturnsDistinctResults:YES ];
// [request setEntity:entity];
[sortDescriptors release];
[sortDescriptor release];
[request setPropertiesToFetch:[NSArray arrayWithObject:#"releaseDate"]];
NSMutableArray *arrOfdMovies = [[self.managedObjectContxt executeFetchRequest:request error:&error]mutableCopy];
[self setArrOfFetchdMovies:arrOfdMovies];
arrOfDistinctYr = [[NSMutableArray alloc]init];
NSMutableArray *temp = [[NSMutableArray alloc]init];
for (int i = 0; i<[arrOfdMovies count]; i++) {
// NSLog(#"%#",[[arrOfdMovies objectAtIndex:i] valueForKey:#"releaseDate"]);
//date to its components
NSDate *now = [[arrOfdMovies objectAtIndex:i]valueForKey:#"releaseDate"];
// Specify which units we would like to use
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *component_s = [calendar components:units fromDate:now];
NSInteger year = [component_s year];
NSLog(#"%i", year);
// NSInteger month = [components month];
// NSInteger day = [components day];
NSNumber *num= [NSNumber numberWithInteger:year];
[temp addObject:num];
}
[self setArrOfDistinctYr:temp];
//distinct value logic.
NSSet *uniqueYrs = [NSSet setWithArray:arrOfDistinctYr];
arr = [[NSArray alloc]initWithArray:[uniqueYrs allObjects]];
//sorting
NSArray *ar = [arr sortedArrayUsingSelector:#selector(compare:)];
self.arr = ar;
[self.managedObjectContxt retain];
[request release];
}
the array "ar" contains only years in distinct and sorted manner. But data types of this array elements are "NSNumbr"
Now How can i form a predicate which will make use of this array to display records for the particular year(how to check year from date field of core data [which has date say- 2006-01-26]).
I tried in following way -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// return 2;
NSFetchRequest *requst=[[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Movies" inManagedObjectContext:self.managedObjectContxt];
[requst setEntity:entity];
requst.predicate = [NSPredicate predicateWithFormat:#"releaseDate CONTAINS%#", [arr objectAtIndex:section]];
NSError *error = nil;
NSMutableArray *array = [[self.managedObjectContxt executeFetchRequest:requst error:&error]mutableCopy];
[requst release];
return [array count];
}
Once i get this, i can display records n my viewController.
One of the way is - Knowing the year, you could get start of the year 2006-01-01 and end of the year 2006-12-31. And then filter for dates that are between them.
For creating predicates - Have a look at Predicate Guide
It has few good example, including some dealing with NSDate predicates.

How To Search For NSDate?

I have an NSDate I want to search for in my predicate. However, the timing may not be 2009-12-06 00:00:00 +0000 but may look more like 2009-12-06 3:05:90 +0000. So how can I search for any date that fits within the bounds of that day (24 hours).
Edit:
These are the related methods to the crash:
Crash is happening in this method related to the Calendar's API framework
- (void) reactToTouch:(UITouch*)touch down:(BOOL)down
{
...
if ([marks count] > 0) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}else{
[self.dot removeFromSuperview];
}
...
}
This graph sets the graph's date and dots for the date if there is data for that date
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {
NSLog(#"calendarMonthView marksFromDate toDate");
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch :[NSArray arrayWithObject:#"timeStamp"]];
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
NSArray *tempData = [objects valueForKey:#"timeStamp"];
NSMutableArray * data1 = [NSMutableArray array];
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSUInteger flags = ( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit );
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
[tempData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDate * date = [gregorian dateFromComponents:[gregorian components:flags fromDate:obj]];
[data1 addObject:[formatter stringFromDate:date]];
}];
self.data = data1;
// Initialise empty marks array, this will be populated with TRUE/FALSE in order for each day a marker should be placed on.
NSMutableArray *marks = [NSMutableArray array];
// Initialise calendar to current type and set the timezone to never have daylight saving
NSCalendar *cal = [NSCalendar currentCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDateComponents *comp = [cal components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:startDate];
NSDate *d = [cal dateFromComponents:comp];
// Init offset components to increment days in the loop by one each time
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
// for each date between start date and end date check if they exist in the data array
while (YES) {
// Is the date beyond the last date? If so, exit the loop.
// NSOrderedDescending = the left value is greater than the right
if ([d compare:lastDate] == NSOrderedDescending) {
break;
}
// If the date is in the data array, add it to the marks array, else don't
if ([data containsObject:[d description]]) {
[marks addObject:[NSNumber numberWithBool:YES]];
} else {
[marks addObject:[NSNumber numberWithBool:NO]];
}
// Increment day using offset components (ie, 1 day in this instance)
d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
}
[offsetComponents release];
[request release];
return [NSArray arrayWithArray:marks];
}
And finally, this is the method we came up with, that pushes to the detail view when a date is selected:
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(#"calendarMonthView didSelectDate");
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString * dateString = [formatter stringFromDate:d];
if ( [data containsObject:dateString] )
{
NSDate * searchDate = [formatter dateFromString:dateString];
NSCalendar * calendar1 = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar1 dateByAddingComponents:dateComponents toDate:searchDate options:0];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
[request setPredicate: predicate1];
[request setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"xxx array: %#", array);
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
self.selectedSession = (Session *)[array objectAtIndex:0];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
sessionViewController.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
[sortDescriptor release];
[request release];
[sortDescriptors release];
}
}
Edit:
When I log the the dates,
The rawDate is straight session.timeStamp and dateString has a date formatter of [dateFormatter setDateFormat:#"eeee, MMM d, y"];
2011-06-27 20:13:44.936 Curl[18714:707] dateString: Monday, Jun 27, 2011
2011-06-27 20:13:44.941 Curl[18714:707] rawString: 2011-06-27 07:05:01 +0000
2011-06-27 20:13:44.961 Curl[18714:707] dateString: Thursday, Jun 23, 2011
2011-06-27 20:13:44.965 Curl[18714:707] rawString: 2011-06-23 08:12:49 +0000
2011-06-27 20:13:44.977 Curl[18714:707] dateString: Wednesday, Jun 22, 2011
2011-06-27 20:13:44.983 Curl[18714:707] rawString: 2011-06-22 21:23:08 +0000
2011-06-27 20:13:44.993 Curl[18714:707] dateString: Tuesday, Jun 21, 2011
2011-06-27 20:13:44.997 Curl[18714:707] rawString: 2011-06-22 03:23:51 +0000
2011-06-27 20:13:45.007 Curl[18714:707] dateString: Monday, Jun 20, 2011
2011-06-27 20:13:45.011 Curl[18714:707] rawString: 2011-06-21 01:03:53 +0000
2011-06-27 20:13:45.020 Curl[18714:707] dateString: Friday, Jun 17, 2011
2011-06-27 20:13:45.024 Curl[18714:707] rawString: 2011-06-18 01:03:53 +0000
Adding a day to searchDate can be done with NSDateComponents using the code below.
NSCalendar * calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents * dateComponents = [[[NSDateComponents alloc] init] autorelease];
[dateComponents setDay:1];
NSDate * searchDateEnd = [calendar dateByAddingComponents:dateComponents
toDate:searchDate
options:0];
Add this after you get the searchDate.
You might also want to change the predicate to
NSPredicate * predicate1 = [NSPredicate predicateWithFormat:#"timeStamp >= %# AND timeStamp < %#", searchDate, searchDateEnd];
Don't check for equality with the upper limit.
Edit
If you look at the code below,
if ([marks count] > 0) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}
You don't have checks on the index and since this seems to represent values pertaining to days in a month, I would suggest you check if there is a valid value.
int size = [marks count];
if ((size > 0) && ((row * 7 + column) < size)) {
if([[marks objectAtIndex: row * 7 + column] boolValue])
[self.selectedImageView addSubview:self.dot];
else
[self.dot removeFromSuperview];
}

Change NSDateFormatter For Dates in Array?

Right now my dates look like this:`2011-01-01 5:45:23 +0000
I want them to look like this: 2011-01-01 00:00:00 +0000 (notice how everything is 00 beside the date, month, and year).
I have an array of NSdates which is fetched from this code:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES]; //set to YES if you only want unique values of the property
[request setPropertiesToFetch :[NSArray arrayWithObject:#"timeStamp"]]; //name(s) of properties you want to fetch
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
NSArray *data = [objects valueForKey:#"timeStamp"];
NSLog(#"The content of data is%#", data);
I want to remove daylight savings and have 0:00:00 for the time aspect of each date, thus I need this NSDateFormatter method:
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"]; // e.g., set for mysql date strings
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString* mysqlGMTString = [formatter stringFromDate:[NSDate date]];
So how can I combine the two to work together?
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
for (NSDate *d in data) {
NSString* mysqlGMTString = [formatter stringFromDate:d];
// ...
}
[formatter release];
Since your requirement is to have strings in the data array, this code should suit your purpose.
NSMutableArray * resultsArray = [NSMutableArray array];
NSCalendar * gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSUInteger flags = ( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit );
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
[datesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDate * date = [gregorian dateFromComponents:[gregorian components:flags fromDate:obj]];
[resultsArray addObject:[formatter stringFromDate:date]];
}];
resultsArray will contain the strings that you need. Now you can have data referring to the object
As for the search with a date part,
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
// Assuming `data` is from the code above & the date is in `00:00:00 +0000` form.
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSString * dateString = [formatter stringFromDate:d];
if ( [data containsObject:dateString] ) {
// Push object to detail view??
}
}
Also use yyyy instead of YYYY. They are not the same.