I have this problem. I have a operation. But if i want to save?
I want to save all (textfield data picker and result in a label)
I have 2 textfield and 1 datapicker + the result in a Label.
this is my M :
#import "ViewController.h"
#import "ResultViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myLabel;
-(IBAction)calculate:(id)sender{
NSDate *past = _data.date ;
NSDate *now = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:past
toDate:now
options:0];
int z = [components day];
int a = ([_textField1.text intValue]);
int b = a*([_textField2.text intValue]);
int r = b * z / 20;
myLabel.text = [[NSString alloc] initWithFormat:#"%d", r];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *past = _data.date ;
NSDate *now = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:past
toDate:now
options:0];
int z = [components day];
int a = ([_textField1.text intValue]);
int b = a*([_textField2.text intValue]);
int r = b * z / 20;
myLabel.text = [[NSString alloc] initWithFormat:#"%d", r];
self.textField1.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key1"];
self.textField2.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key2"];
self.myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key3"];
self.data = [[NSUserDefaults standardUserDefaults] objectForKey:#"key4"];
[[NSUserDefaults standardUserDefaults]synchronize];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detail"]) {
ResultViewController* destVC = (ResultViewController*)segue.destinationViewController;
destVC.myString = self.myLabel.text;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:YES];
[[NSUserDefaults standardUserDefaults] setObject:self.textField1.text forKey:#"key1"];
[[NSUserDefaults standardUserDefaults] setObject:self.textField2.text forKey:#"key2"];
[[NSUserDefaults standardUserDefaults] setObject:self.myLabel.text forKey:#"key3"];
[[NSUserDefaults standardUserDefaults] setObject:self.data forKey:#"key4"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
#end
This code is Right?
Thank you....
Couple things.
In your -viewDidLoad, you call -synchronize for some reason. All this does is perform the save function for any events on your user defaults. From what I can see, you don't have any and can skip this call to -synchronize.
One of your logs is showing the value of 'r'. The value is an int value and you should use '%i' to display this correctly. You are performing some calculations to get that value, so you may want that to be a double or something else, but you are currently casting it to an int.
I don't see anything regarding the user defaults that looks out of sorts. So maybe you can specify what exactly is wrong or isn't being done correctly to get some better help.
Yes code looks right.
What is your _data variable type?
If you having trouble saving to NSUser. Try to save self.data.date
One tip : You don't need to synchronize after getting values from NSUserdefautls. Use synchronize after setting values to NSUserdefaults.
Related
I have a part of app that set date and time of an appointment. For this, I have two NSDatePickerView. The first one I set to NSDatePickerModeDate, while the other one to NSDatePickerModeTime. But actually they should be referring to a same NSDate object inside a NSMutableDictionary entry. I know about NSDatePickerModeDateTime, but I need the date and time to be picked separatedly.
I know how to set up the NSDatePickerView to show and hide and event control and such, but at the event control UIControlEventValueChanged fire for NSDatePickerView, I'm confused on how to code the change for this, and also how to initialise the pickers (datePicker.date = today, timePicker.date = "9:00 AM")
#interface MyViewController () {
NSMutableDictionary *data;
}
#end
#implementation MyViewController
#synthesize datePicker, timePicker;
- (void) viewDidLoad {
[super viewDidLoad];
data = [[NSMutableDictionary alloc] init];
[data setObject:[NSDate date] forKey:#"date"];
datePicker.datePickerMode = UIDatePickerModeDate;
timePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:#selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[timePicker addTarget:self action:#selector(changeTime:) forControlEvents:UIControlEventValueChanged];
datePicker.date = data[#"date"]; //????
timePicker.date = data[#"date"]; //????
}
- (IBAction) changeDate:(id)sender {
UIDatePickerView *dp = (UIDatePickerView *)sender;
[data setObject:dp.date forKey:#"date"]; //????
}
- (IBAction) changeTime:(id)sender {
UIDatePickerView *tp = (UIDatePickerView *)sender;
[data setObject:tp.date forKey:#"date"]; //????
}
The part that I don't know how to code it is denoted by //????. I've read about NSDateFormatter, NSCalendar, and some kind of date components on some answers, but that was actually making me more confused as it also throws strings and structs into the mix, what to use to do what and when. Please help.
You can set both date pickers to the same date and time. The unused part is there but it isn't displayed and can't be changed. When the user changes the value of one date picker you have to set the other date picker to the same value.
- (IBAction)changeDate:(id)sender {
NSDatePicker *dp = (NSDatePicker *)sender;
[data setObject:dp.dateValue forKey:#"date"];
self.timePicker.dateValue = dp.dateValue;
}
- (IBAction)changeTime:(id)sender {
NSDatePicker *tp = (NSDatePicker *)sender;
[data setObject:tp.dateValue forKey:#"date"];
self.datePicker.dateValue = tp.dateValue;
}
u can try this
///Convert Full date to only date
- (IBAction) changeDate:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"date"];
}
///convert Date to only time format
- (IBAction) changeTime:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"Time"];
}
Can anyone tell me please how to save only date value to Core Data using objective C? I am using UIDatePicker. I searched a lot, but couldn't find any. Can you be more specific because i am newbie. Thanks
Here is my code for adding data to core data database. But instead of formatting dates into string I would like to save as a NSdate. I am creating an calendar app that stores events into CoreData. Is there any help?
- (IBAction)btnSave:(UIBarButtonItem *)sender {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *dataRecord = [NSEntityDescription insertNewObjectForEntityForName:#"Scheduler" inManagedObjectContext:context];
[dataRecord setValue:self.txtBxCustomerName.text forKey:#"customerName"];
[dataRecord setValue: [self date] forKey:#"date"];
[dataRecord setValue:[self begin] forKey:#"startTime"];
[dataRecord setValue:[self end] forKey:#"endTime"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Error! %#", error);
}
[self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)datePicker:(id)sender {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *string = [dateFormat stringFromDate:self.dateTime.date];
date = string;
}
- (IBAction)startTimePicker:(id)sender {
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm"];
NSString *str = [timeFormat stringFromDate:self.startTime.date];
begin = str;
}
- (IBAction)endTimePicker:(id)sender {
NSDateFormatter *endTimeFormatt = [[NSDateFormatter alloc] init];
[endTimeFormatt setDateFormat:#"HH:mm"];
NSString *sting = [endTimeFormatt stringFromDate:self.endTime.date];
end = sting;
}
Get the date from the picker with
NSDate *chosenDate = myDatePicker.date;
and then set it to the desired attributed (in the example startDate) of your model, which should be define in Core Data as type Date
myCoreDataObject.startDate = chosenDate;
or even shorter
myCoreDataObject.startDate = myDatePicker.date;
I have a UISwitch on my UITableViewCell (Custom cell) that is activating switches on other cells without any touch, I don't really know why (I don't have any code activating switches on my cells).
(source: abril.com)
.
(source: abril.com)
.
Code:
//Creating cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
CustomClassCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[CustomClassCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
NSDictionary *classDetail = [self.classesArray objectAtIndex:indexPath.row];
cell.textLabel.text = [classDetail objectForKey:#"nome"];
NSString *detailText = [NSString stringWithFormat:#"Professor %# às %#. %# minutos",[classDetail objectForKey:#"professor"], [classDetail objectForKey:#"hora"], [classDetail objectForKey:#"duracao"] ];
NSString *weekDayString = [[self.viewData objectForKey:#"#attributes"] objectForKey:#"index"];
cell.weekDay = [weekDayString integerValue];
cell.detailTextLabel.text = detailText;
cell.cellData = classDetail;
return cell;
}
//CustomClassCell.m
//This action is linked via storyboard to Value Changed on my UISwitch:
-(IBAction)isOn:(id)sender{
UISwitch *switcher = sender;
BOOL isOn = [switcher isOn];
(isOn == YES ? [self activeNotification] : [self deactiveNotification]);
}
-(void)activeNotification{
NSString *classTimeString = [self.cellData objectForKey:#"hora"];
NSArray *hourAndMinutes = [classTimeString componentsSeparatedByString:#":"];
int hour = [[hourAndMinutes objectAtIndex:0] intValue];
int minutes = [[hourAndMinutes objectAtIndex:1] intValue];
UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit) fromDate: now];
now = [gregorian dateFromComponents:components];
NSDate *alarmDate = [self getDayFromNumber:self.weekDay fromToday:now];
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*minutes];
if (([now compare:alarmDate] == NSOrderedAscending) || ([now compare:alarmDate] == NSOrderedSame) ){
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*(minutes - 30)];
} else {
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*(minutes - 30) + 60*60*24*7];
}
locNot.fireDate = alarmDate;
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
}
-(void)deactiveNotification{
//TODO: implement deactivation
}
-(NSDate *)getDayFromNumber:(NSInteger)number fromToday:(NSDate *)today{
number++;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:today];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - number)];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
toDate:today options:0];
NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit) fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents:components];
return beginningOfWeek;
}
Any ideas?
Regards!
This is a cell reuse problem because you are reusing cells but you aren't configuring the switch status (which should be done when you configure the cell text).
This requires that you update your source data (classDetail / cellData) as the switches change so that you can use that information later when returning cells. This is both to prevent duplication of changes and the ensure that a selected switch doesn't change to a deselected switch after a cell is scroll off-screen.
Im trying to load an events(data) (from json file) that matches today's date into my tableView when the today's button is pressed then only the data with today's date will be loaded there and when the future button is pressed the events with later dates will be loaded, the only problem I have here is when i run my program nothing is actually happening when I press in either of these UIbuttons, I got all the events regardless their date and without even clicking on any UIButton, u can see below some of my code, it would be great if someone could figure out what is the problem there and since Im not quiet sure about how to use predicate to filter the data:
#property (strong, nonatomic) NSArray *dateEvents;
#end
#implementation HomeViewController {
NSArray *_events;
NSArray *_dateEvents;
}
- (IBAction)upcomingEvents:(id)sender {
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"mama");
_dateEvents = [_events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Events * event, NSDictionary *bindings){
return [event.date isEqualToString:dateString];
}]];
self.myTableView.dataSource = self;
[self.myTableView reloadData];
NSLog(#"yes");
}
Thanks,
I'm not sure this will definitely help, because I can't see enough code so be certain that this is your problem, but you might find it useful to convert all the dates to NSDate objects (so that you can be certain that the problem is NOT that the strings are actually not equal), and then check whether the day is the current day, or not, by using this category method on NSDate:
NSDate+Extensions.m:
static NSCalendar* ___calendar;
#implementation NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:self];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
-(NSCalendar*)currentCalendar
{
if(___calendar == nil)
{
___calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
}
return ___calendar;
}
#end
NSDate+Extensions.h
#interface NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date;
#end
I have an image that i want to display as a sun during daytime i.e. from 6am to 6pm, and moon from 6pm to 6am.
I have successfully implemented that but the problem is the image would not change when it reaches the specified time unless re-run the apps before the image change itself.
I don't want to use NSTimer to check the time, like every second. The only possible solution i think of is using NSLocalNotification but I'm a newbiew to it. any help? =)
-(void) dayOrNight
{
NSDate* date = [NSDate date];
NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HHmm"];
NSString* dateString = [dateFormat stringFromDate:date];
NSNumber* currentTime = [NSNumber numberWithInt:[dateString intValue]];
NSNumber* daytime = [NSNumber numberWithInt:600];
NSNumber* nightime = [NSNumber numberWithInt:1800];
NSLog(#"current time: %#",dateString);
dayNight = [[UIImageView alloc] initWithFrame:CGRectMake(265, 10, 50, 50)];
if ( [currentTime doubleValue] >= [daytime doubleValue] && [currentTime doubleValue] <= [nightime doubleValue] )
{
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
else
{
dayNight.image = [UIImage imageNamed:#"moon.png"];
}
[self.view addSubview:dayNight];
}
Local notification should be fine, I guess.
Here you can get all needed code snippets to implement execution of dayOrNight method at needed time. Also, you shouldn't add new view every time you change the picture.
I think it is impossible to do without NSTimer. U can set refreshTime by yourself (for example 1 min/ if u don`t want to do it every second)))
Or u can call this method in other methods, which are working in your class every time...
maybe u have some object, which u use during your class is working...
-(IBAction)myButtonWhichIPressDuringIworkHere {
///some actions
[self dayOrNight];
}
In other case you should to use NSTimer
you don't need to check the time at every second.
this is one of the possible solutions. it has been tested on real device only.
your UIYourViewController.m
- (void)viewWillAppear:(BOOL)animated {
NSDate *_currentDate = [NSDate date];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00AM +0000'"]; // set the morning date here
NSString *_morningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00PM +0000'"]; // set the evening date here
NSString *_eveningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd hh:mma zzz"];
NSDate *_morningDate = [_dateFormatter dateFromString:_morningDateString];
NSDate *_eveningDate = [_dateFormatter dateFromString:_eveningDateString];
NSTimeInterval _intervalToMorningDate = [_morningDate timeIntervalSinceDate:_currentDate];
NSTimeInterval _intervalToEveningDate = [_eveningDate timeIntervalSinceDate:_currentDate];
if (_intervalToMorningDate > 0) {
// now it is night
dayNight.image = [UIImage imageNamed:#"moon.png"];
[self performSelector:#selector(replaceTheBackgoundForMorning) withObject:nil afterDelay:_intervalToMorningDate];
} else {
// now it is daytime
dayNight.image = [UIImage imageNamed:#"Sun.png"];
[self performSelector:#selector(replaceTheBackgoundForEvening) withObject:nil afterDelay:_intervalToEveningDate];
}
}
- (void)viewDidDisappear:(BOOL)animated {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
and finally you should add them to your same .m file:
-(void)replaceTheBackgoundForMorning {
// reaplce the backgound here
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
- (void)replaceTheBackgoundForEvening {
// reaplce the backgoung here
dayNight.image = [UIImage imageNamed:#"moon.png"];
}