date conversion to string xcode - xcode

I'm developing an app which displays start date and end date, but I'm having an issue with date displayed on textfield
everything works fine here:
but when I turn to December 30 2012 in output you can read that says 2012 (Hardcoded) but in textfield it writes 2013 (formatted):
happens the same thing if I try using "All day" option:
gonna share my app code as well for making things easier
#import "StartEndEventVC.h"
#import "visitVC.h"
#import "Functions.h"
#interface StartEndEventVC ()
{
NSDate *date;
NSDateFormatter *df;
NSString *selectedCell;
}
#property (nonatomic, strong) Functions *funciones;
#end
#implementation StartEndEventVC
#synthesize funciones = _funciones;
#synthesize datePicker = _datePicker,
SwitchDate = _SwitchDate,
fecFinDateSE = _fecFinDateSE,
fecInicioDateSE = _fecInicioDateSE;
#pragma mark *** Common methods ***
- (void)viewDidLoad
{
[super viewDidLoad];
//Datepicker initial settings
self.datePicker.timeZone = [NSTimeZone localTimeZone];
self.datePicker.locale = [NSLocale currentLocale];
self.datePicker.calendar = [NSCalendar currentCalendar];
//Date format initial settings
df = [NSDateFormatter new];
[df setDateFormat:#"EE, dd MMM YYYY HH:mm a"];
[df setTimeZone:[NSTimeZone localTimeZone]];
//initial cell to interact with datepicker
selectedCell = #"startDate";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"back"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(didBack:)];
}
-(void)estableceFechaCamposTexto{
self.fecInicioDateSE = [[NSDate alloc]init];
self.fecFinDateSE = [[NSDate alloc]init];
self.fecInicioDateSE = [NSDate date];
self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60];
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
}
-(void)viewDidAppear:(BOOL)animated{
if ((self.fecInicioDateSE == nil) || (self.fecFinDateSE == nil)) [self estableceFechaCamposTexto];
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
}
-(Functions *)funciones{
if (!_funciones) _funciones = [[Functions alloc]init];
return _funciones;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"doneStartEnd"]) {
[segue.destinationViewController setFecInicioDateV: self.fecInicioDateSE];
[segue.destinationViewController setFecFinDateV: self.fecFinDateSE];
NSLog(#"fecha inicio StartEvent: %#", self.fecInicioDateSE);
NSLog(#"fecha fin StartEvent: %#", self.fecFinDateSE);
}
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.row) {
case 0:
selectedCell = #"startDate";
self.datePicker.date = self.fecInicioDateSE;
break;
case 1:
selectedCell = #"endDate";
self.datePicker.date = self.fecFinDateSE;
default:
break;
}
}
#pragma mark -
#pragma mark *** Custom methods ***
-(void)comparaFechaInicio{
if ([self.fecInicioDateSE timeIntervalSinceDate:self.fecFinDateSE] >= 0) {
if (self.SwitchDate.on) self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60*24];
else
if(!(self.SwitchDate.on)) self.fecFinDateSE = [self.fecInicioDateSE dateByAddingTimeInterval:60*60];
}
self.startDateLabel.text = [df stringFromDate:self.fecInicioDateSE];
self.endDateLabel.text = [df stringFromDate:self.fecFinDateSE];
NSLog(#"Hardcoded date: %#", self.fecInicioDateSE);
NSLog(#"formatted date: %#", [df stringFromDate:self.fecFinDateSE]);
}
- (void) didBack:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark *** Button actions ***
-(IBAction)adjustDate:(id)sender{
if ([selectedCell isEqualToString:#"startDate"]){
self.fecInicioDateSE = [self.datePicker date];
[self comparaFechaInicio];
}
else
if ([selectedCell isEqualToString:#"endDate"]){
self.fecFinDateSE = [self.datePicker date];
self.endDateLabel.text = [df stringFromDate:self.datePicker.date];
}
}
- (IBAction)saveChanges:(id)sender {
[self comparaFechaInicio];
[self performSegueWithIdentifier:#"doneStartEnd" sender:self];
}
-(IBAction)changeDateType:(id)sender{
if (self.SwitchDate.on){
self.datePicker.datePickerMode = UIDatePickerModeDate;
[df setDateFormat:#"EE, dd MMM YYYY"];
}
else{
self.datePicker.datePickerMode = UIDatePickerModeDateAndTime;
[df setDateFormat: #"EE, dd MMM YYYY HH:mm a"];
}
[self comparaFechaInicio];
}
#pragma mark -
#end

You fell in the same trap that Apple did with recent their Do Not Disturb bug. You want to use yyyy in your NSDateFormatter, not YYYY.

Related

issue loading core data into uitableview

I have been trying to figure this issue out for days now with no luck, any advice would be greatly appreciated.
I have a uitableviewcontroller that loads data from core data. When the tableview loads, the first 6 (no matter how many objects are actually saved) are loaded. When I begin to scroll down, all of the following cells are labeled "(null)". When I go back up to the top, the data in the original 6 cells are replaced with "(null)". When I logged the contents of the array from the fetch, all of the objects from core data get logged, but when I log the contents of the cell, the first 6 contents get logged, the a long list of rows with (null) get logged.
I've tried a lot of differnet things to debug this, but nothing has worked so far.
Here is the tableviewcontroller file
-(void)viewWillAppear:(BOOL)animated
{
[self setTitle:#"My Safe"];
self.dictionaryWithContent = [[NSMutableDictionary alloc] init];
self.search = #0;
[self fetchDataFromCoreData];
[self.tableView setFrame:CGRectMake(0, 88, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
self.searchResults = [[NSMutableArray alloc] init];
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 44.0f)];
UIBarButtonItem *changeViewsButton = [[UIBarButtonItem alloc] initWithTitle:#"Tweets By User"
style:UIBarButtonItemStylePlain
target:self
action:#selector(switchViewControllers)];
self.navigationItem.rightBarButtonItem = changeViewsButton;
self.tableView.delegate = self;
self.tableView.dataSource = self;
// CGRect searchView = CGRectMake(0, 44, self.tableView.bounds.size.width, 44);
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
[self.searchController loadViewIfNeeded];
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.barTintColor = twitter_blue;
self.searchController.delegate = self;
self.searchController.searchBar.delegate = self;
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:animated];
self.navigationController.navigationBar.barTintColor = twitter_blue;
self.navigationController.navigationBar.translucent = NO;
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationController.navigationBar setTitleTextAttributes:#{NSForegroundColorAttributeName : [UIColor whiteColor]}];
}
-(void)fetchDataFromCoreData
{
AppDelegate *del = [[AppDelegate alloc] init];
NSManagedObjectContext *context = del.managedObjectContext;
NSString *entity;
entity = [NSString stringWithFormat:#"Tweet"];
NSFetchRequest *fet = [NSFetchRequest fetchRequestWithEntityName:entity];
NSError *e;
NSArray *array = [context executeFetchRequest:fet error:&e];
self.arrayWithContent = [[NSArray alloc] initWithArray:array];
for (Tweet *t in self.arrayWithContent) {
NSLog(#"array %#", t.messageOfTweet);
}
}
-(void)switchViewControllers
{
PCRSavedTweetByUserTableViewController *vc = [[PCRSavedTweetByUserTableViewController alloc] init];
PCRNavigationBarController *navBarControllerOfSafeSide = [[PCRNavigationBarController alloc] initWithRootViewController:vc];
[self.navigationController presentViewController:navBarControllerOfSafeSide animated:YES completion:nil];
}
#pragma mark Status bar
- (void)willPresentSearchController:(UISearchController *)searchController {
// do something before the search controller is presented
self.navigationController.navigationBar.translucent = YES;
}
-(void)willDismissSearchController:(UISearchController *)searchController
{
self.navigationController.navigationBar.translucent = NO;
searchController = self.searchController;
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
searchController = self.searchController;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
self.search = #1;
[self.searchResults removeAllObjects];
NSString *searchBarString = self.searchController.searchBar.text;
for (Tweet *tweet in self.arrayWithContent){
if ([tweet.messageOfTweet containsString:searchBarString] || [tweet.userNameOfTweetUser containsString:searchBarString] || [tweet.whoPosted.name containsString:searchBarString]) {
[self.searchResults addObject:tweet];
}
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[self.searchController.searchBar resignFirstResponder];
self.search = #0;
[self.tableView reloadData];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
self.searchController.searchBar.text = #"";
}
#pragma mark Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [self.arrayWithContent count];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 120.0f;
}
- (PCRTweetFeedCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PCRTweetFeedCell *cell = [tableView dequeueReusableCellWithIdentifier:#"PCRSavedTweetFeedCell"];
PCRTweet *tweetLocal = [[PCRTweet alloc] init];
if (cell == nil) {
cell = [[PCRTweetFeedCell alloc] initWithTweet:tweetLocal reuseIdentifier:#"PCRSavedTweetFeedCell"];
}
Tweet *tweetForIndex;
NSArray *arrayForCell = [[self.arrayWithContent reverseObjectEnumerator] allObjects];
NSArray *searchArrayForCell = [[self.searchResults reverseObjectEnumerator] allObjects];
if ([self.search isEqual:#0]){
tweetForIndex = [arrayForCell objectAtIndex:indexPath.row];
} else if ([self.search isEqual:#1]){
tweetForIndex = [searchArrayForCell objectAtIndex:indexPath.row];
}
NSString *date = [NSString stringWithFormat:#"%#", tweetForIndex.dateOfTweet];
TweetUser *tweetUser = tweetForIndex.whoPosted;
cell.t = tweetForIndex;
UIImage *imageOfTweetUser;
if (tweetUser.profilePicture) {
imageOfTweetUser = [UIImage imageWithData:tweetUser.profilePicture];
} else {
NSURL *urlWithProfilePicture = [NSURL URLWithString:tweetUser.profilePictureURL];
NSData *dataWithPic = [NSData dataWithContentsOfURL:urlWithProfilePicture];
imageOfTweetUser = [UIImage imageWithData:dataWithPic];
}
self.imageOfTweetUserGlobal = imageOfTweetUser;
cell.tweetMessage.text = tweetForIndex.messageOfTweet;
cell.tweetDate.text = date;
cell.tweetUserNameLabel.text = tweetForIndex.userNameOfTweetUser;
cell.profilePictureOfTwitterUserImageView.image = imageOfTweetUser;
cell.nameForPassing = [NSString stringWithFormat:#"%#'s Tweet", tweetUser.name];
return cell;
}
Well maybe this is your problem.
if ([self.search isEqual:#0]){
I think you are initially fetching the data but than once you init the searchController it starts looking for the searchResults.
The code you are looking is:
if ([self.search isActive]){
I found the solution. I changed
AppDelegate *del = [[AppDelegate alloc] init];
NSManagedObjectContext *context = del.managedObjectContext;
to
AppDelegate *del = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =[del managedObjectContext];
and it works perfectly.

Pause and Resume Time Xcode

I know that there is no way to pause a timer using NSTimer. I know i have to store the date and call it again. I have tried every solution and i cannot find any that have successfully worked. So my question is, does anyone know how to pause and resume?
This worked good for me.
Created 2 UIButtons ('startButton' & 'resetButton'), a UILabel to display time ('timeLabel'), NSTimeInterval ('pauseTimeInterval'), NSTimer (stopWatchTimer') and used the following code:
NSDate *pauseStart, *previousFireDate, *startDate;
NSTimeInterval pauseTimeInterval;
NSTimer *stopWatchTimer;
-(void)pauseTimer{
pauseStart = [NSDate dateWithTimeIntervalSinceNow:0];
previousFireDate = [self fireDate];
[self setFireDate:[NSDate distantFuture]];
}
-(void)resumeTimer{
float pauseTime = -1*[pauseStart timeIntervalSinceNow];
[self setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];
}
-(IBAction)startTime:(id)sender {
//start timer
if ([startButton.titleLabel.text isEqualToString:#"Start"] && (![self.stopWatchTimer isValid]) && ([timeLabel.text isEqualToString:#"00:00:00"]))
{
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
self.stopWatchTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
target:self
selector:#selector(updateTimer)
userInfo:nil
repeats:YES];
resetButton.hidden = YES;
}
//pause timer
else if (([self.stopWatchTimer isValid]) && ([startButton.titleLabel.text isEqualToString:#"Stop"]))
{
[startButton setTitle:#"Resume" forState:UIControlStateNormal];
[self.stopWatchTimer pauseTimer];
resetButton.hidden = NO;
}
//resume timer
else {
[startButton setTitle:#"Stop" forState:UIControlStateNormal];
startDate = [NSDate date];
startDate = [startDate dateByAddingTimeInterval:((-1)*(pauseTimeInterval))];
[self.stopWatchTimer resumeTimer];
resetButton.hidden = YES;
}
}
-(IBAction)resetTime:(id)sender {
[self.stopWatchTimer invalidate];
self.stopWatchTimer = nil;
self.timeLabel.text = #"00:00:00";
[startButton setTitle:#"Start" forState:UIControlStateNormal];
pauseTimeInterval = 0.0;
resetButton.hidden = YES;
}
-(void)updateTimer
{
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
self.timeLabel.text = timeString;
pauseTimeInterval = timeInterval;
}

EventKit saveEvent is not working in iOS 7

I have added following code in my application.It is working fine if [comps setYear:1] but if i change year value to 2 or greater than 2 code does not show me any error but also not adding any event in calender. This happens in iOS 7 only. But if I run the same code on iOS 6 , its working correctly & event gets added in calender successfully. Is there any restriction in iOS 7 for adding future events ?
-(void)addEvent{
EKEventStore *es = [[EKEventStore alloc] init];
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
BOOL needsToRequestAccessToEventStore = (authorizationStatus == EKAuthorizationStatusNotDetermined);
if (needsToRequestAccessToEventStore) {
[es requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
[self setEventForStore:es];
} else {
}
}];
} else {
BOOL granted = (authorizationStatus == EKAuthorizationStatusAuthorized);
if (granted) {
[self setEventForStore:es];
} else {
}
}
}
-(void)setEventForStore:(EKEventStore*)store{
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"Event 4";
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [NSDateComponents new];
// comps.day =3650;
comps.day=5;
comps.hour=1;
comps.year=2;
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
event.startDate = sevenDays;
NSDate *sevenDays1 = [event.startDate dateByAddingTimeInterval:60*60];;
// duration = 1 h
event.endDate = sevenDays1;
[event setCalendar:[store defaultCalendarForNewEvents]];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}
`
Whenever dealing with dates through components, please set them in the following fashion:
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setDay:05];
[comps setMonth:01];
[comps setYear:2014]; //instead of adding a single digit number like so: 2
//followed by your code...
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//...
UPDATE 1
You mentioned that your event is not being saved in the calendar when you slightly adjust the integer values in your NSDate's components. One quick way to see whats happening is by NSLogging your date. See what the ouput is before you try to add it to your calendar.
//Right after this below line
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0];
//Add the code here so we can see what `sevenDays` prints out.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:sevenDays];
NSLog(#"Seven Days date = %#", strDate);

TableViewController Vs UIViewController and a tableView inside

I have a Master/Details Application.By default, we have the MasterViewController attached to a TableViewController, in addition, i have attached it to an Sqlite database and all the data are showing correctly as they should. So i added a UISearchBar, in order to search upon all the items ; Search functionality's were working fine but the only bug was, the search bar disappears when scrolling down. So as a solution, i removed the TableViewController and created a simple UIVIewController and added a TableView , TableViewCell and a search bar in order to keep the search bar fix on top of the View as suggested by many people.Now the difference between those two concepts is, the TableViewController (First Case) loads the whole data in the cells once the application loads, when the ViewController ( Second Case , with a tableView , tableViewCell and a searchBar) does not load anything at startup, It loads the different elements when the user start writing a word in the searchBar. How can i force the tableView to load all Elements at startup, just like if you have a TableViewCOntroller?
This is my code :
//
// MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import <sqlite3.h>
#import "Author.h"
#interface MasterViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation MasterViewController
NSString *authorNAme , *authorNAme2;
#synthesize tableView;
#synthesize searchWasActive;
#synthesize detailViewController = _detailViewController;
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize theauthors;
NSString *PathDB;
-(BOOL)canBecomeFirstResponder{
return YES;
}
- (void)awakeFromNib
{
// self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}
- (void)viewDidLoad
{
// [self numberOfSectionsInTableView:tableView];
//[self tableView:tableView willDisplayCell:[self.tableView dequeueReusableCellWithIdentifier:#"Cell"] forRowAtIndexPath:0];
//[self.tableView
searchBar.delegate = (id)self;
// [self.tableView reloadData];
// [self configureCell:#"Cell" atIndexPath:0];
[self authorList];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}
- (void)viewDidUnload
{
[self setTableView:nil];
tableView = nil;
searchBar = nil;
[self setSearchWasActive:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//[self authorList];
// [filteredTableData release];
//[self.tableView reloadData];
NSLog(#"Cancel Button Clicked");
// Scroll to top
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
self.searchDisplayController.searchBar.text =#" ";
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)sender
{
[self.tableView reloadData];
searchBar.showsCancelButton=NO;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
searchBar.showsCancelButton=NO;
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Author* author in theauthors)
{ //[NSPredicate predicateWithFormat:#"SELECT * from books where title LIKE %#", searchBar.text];
NSRange nameRange = [author.name rangeOfString:text options:NSAnchoredSearch];
NSRange descriptionRange = [author.genre rangeOfString:text options:NSAnchoredSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:author];
NSLog(#"Item Added is %#" , author.name);
}
}
}
[self.tableView reloadData];
}
#pragma mark - Table View methods
-(NSMutableArray *) authorList{
[self numberOfSectionsInTableView:tableView];
theauthors = [[NSMutableArray alloc] initWithCapacity:1000000];
// NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000];
// authorNAme = theauthors.sortedArrayHint.description;
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSLog(#"Before the dbpath variable");
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary_native.sqlite"];
NSLog(#"After the dbpath variable");
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"1");
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
NSLog(#"Database correctly located");
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"2");
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
NSLog(#"Database correctly opened");
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM wordss";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
// NSLog(#"entered the while statement");
Author * author = [[Author alloc] init];
// // NSLog(#"Author initialised");
//
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
// NSLog(#"this is the author.name %#" , author.name);
author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
//
// authorNAme=author.genre;
//
[theauthors addObject:author];
}
// authorNAme = author.genre;
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
// authorNAme = Nil;
return theauthors;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
// return [sectionInfo numberOfObjects];
int rowCount;
if(self->isFiltered)
rowCount = filteredTableData.count;
else
rowCount = theauthors.count;
NSLog(#"This is the number of rows accepted %i" , rowCount);
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int rowCount = indexPath.row;
Author *author = [self.theauthors objectAtIndex:rowCount];
if(isFiltered){
author = [filteredTableData objectAtIndex:indexPath.row];
}
else{
author = [theauthors objectAtIndex:indexPath.row];
}
cell.textLabel.text = author.name;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
// self.detailViewController.detailItem = object;
// DetailViewController* vc ;
MasterViewController *author;
NSLog(#"This is the showDetailsForIndexPath");
[self->searchBar resignFirstResponder];
// Details* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"Details"];
// AuthorVC* author;
if(isFiltered)
{
author = [filteredTableData objectAtIndex:indexPath.row];
}
else
{
author = [theauthors objectAtIndex:indexPath.row];
}
//vc.author = author;
authorNAme = author.genre;
authorNAme2 = author.name ;
// author = [theauthors objectAtIndex:indexPath.row];
NSLog(#"This is the author.genre %#" , author.genre);
//vc.author.genre = author.genre;
authorNAme = author.genre;
authorNAme2 = author.name;
//NSLog(#"This is the details %#",vc.author.genre);
NSLog(#"This is the authorNAme Variable %#" , authorNAme);
self.detailViewController.detailItem = authorNAme;
self.detailViewController.detailItem2 = authorNAme2;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
// UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
// cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
#end
Any help Will be highly appreciated...Thank you for taking the time.
If the tableview is in xib link it to correct object and set delegate and datasource.

How to select multiple dates in TapKu library?

I would like to show the multiple selected dates in tapkilibrary .like highlight the dates between 14aug2011 to 18aug2011 .
-(NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate{
NSLog(#"Date Selected is %#",date);
//txtbdate.text=date;
NSDateFormatter *timeFormat = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[timeFormat setDateFormat:#"yyyy-MM-dd"];
[timeFormat setTimeZone:gmt];
//[timeFormat setLocale:[NSLocale currentLocale]];
//[timeFormat setTimeZone:[NSTimeZone localTimeZone]];
NSString *theTime = [timeFormat stringFromDate:date];
NSLog(#"%#",theTime);
objappdel.strdate=theTime;
[tkmonthView reload];
AppointmentDetail *appointmentDetail=[[AppointmentDetail alloc]initWithNibName:#"AppointmentDetail" bundle:nil];
[self.navigationController pushViewController:appointmentDetail animated:YES];
[appointmentDetail release];
}
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate
{
NSMutableArray * data = [[NSMutableArray alloc] init];
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateForm setDateFormat:#"yyyy-MM-dd"];
[dateForm setTimeZone:gmt];
NSDate *date ;
for (int i=0; i<[objappdel.arrDate count]; i++)
{
NSString *time;
time=[objappdel.arrDate objectAtIndex:i];
//time= [[[jobData valueForKey:#"Record"] objectAtIndex:i] valueForKey:#"JobStartDate"];
//time = [[time componentsSeparatedByString:#" "] objectAtIndex:0];
date = [dateForm dateFromString:time];
[data addObject:[NSString stringWithFormat:#"%#",date]];
}
NSArray *copy = [data copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
if ([data indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)
{
[data removeObjectAtIndex:index];
}
index--;
}
NSLog(#"sorted dates are %#",copy);
// 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]];
// Construct DateComponents based on startDate so the iterating date can be created.
// Its massively important to do this assigning via the NSCalendar and NSDateComponents because of daylight saving has been removed
// with the timezone that was set above. If you just used "startDate" directly (ie, NSDate *date = startDate;) as the first
// iterating date then times would go up and down based on daylight savings.
NSDateComponents *comp = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | 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
//NSLog(#"%#",[d description]);
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];
return [NSArray arrayWithArray:marks];
}
Use this delegate method. It will return an NSArray of dates which you want to highlight.
You can do this by first entering the dates in to an array. code for this is.
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(#"selected Date IS - %#",inDate);
[myArray addObject:d];
for (id entry in myArray)
{
if (inDate == nil && outDate == nil)
{
inDate = d;
outDate = d;
}
if ([d compare:inDate] == NSOrderedAscending)
{
inDate = d;
}
if ([d compare:outDate] == NSOrderedDescending)
{
outDate = d;
}
d = nil;
}
}
After this you have to use a button click action by which you can make the dates selected between these two dates. Code for it is:
- (IBAction)goBtn:(id)sender
{
NSLog(#"startDate is: %#",inDate);
NSLog(#"endDate is: %#",outDate);
[calendar reload];
inDate = nil;
outDate = nil;
}
}
Then in one delegate method you just have to make an array containing all the dates between these two dates. It will be called just after the button click. Code for it is:
- (NSArray*)calendarMonthView:(TKCalendarMonthView *)monthView marksFromDate:(NSDate *)startDate toDate:(NSDate *)lastDate {
//***********
NSMutableArray *tempData = [[NSMutableArray alloc] init];
NSDate *nextDate;
for ( nextDate = inDate ; [nextDate compare:outDate] < 0 ; nextDate = [nextDate addTimeInterval:24*60*60] ) {
// use date
NSLog(#"%#",nextDate);
[tempData addObject:[NSString stringWithFormat:#"%#",nextDate]];
}
[tempData addObject:[NSString stringWithFormat:#"%#",outDate]];
//***********
NSMutableArray *marks = [NSMutableArray array];
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];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:1];
while (YES) {
if ([d compare:lastDate] == NSOrderedDescending) {
break;
}
if ([tempData containsObject:[d description]]) {
[marks addObject:[NSNumber numberWithBool:YES]];
} else {
[marks addObject:[NSNumber numberWithBool:NO]];
}
d = [cal dateByAddingComponents:offsetComponents toDate:d options:0];
}
return [NSArray arrayWithArray:marks];
}
I hope, this helped you. Please let me know if you face any problem.

Resources