我在从选择器中选择我的日期并向其添加通知时遇到问题

时间:2011-09-08 05:44:44

标签: iphone objective-c

我在我的应用程序中以编程方式创建了一个日期选择器。当我从我的日期选择器中选择任何时间并单击添加按钮时,日期会被添加到我之前控制器的cell.detailtext标签中,并且该日期会被添加到通知应被触发的通知日期。但是我在解决通知时遇到了问题。当我设置日期时,它会在我点击添加按钮后立即显示通知。这是我从代码中获取日期的代码。

这是我的控制器类,我在其中创建了我的选择器。

- (void)viewDidLoad {
   time = [[NSString alloc] init]; 
   CGRect pickerFrame = CGRectMake(0,40,0,0); 

   datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame]; 
   datePicker.datePickerMode = UIDatePickerModeTime; 
   datePicker.date = [NSDate date];
   [datePicker addTarget:self action:@selector(convertDueDateFormat) forControlEvents:UIControlEventValueChanged]; 
   [self.view addSubview:datePicker]; 
   [datePicker release];
}

-(NSString *)convertDueDateFormat{
   NSDate *pickerDate = self.datePicker.date;

   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
   [dateFormatter setDateFormat:@"hh:mm"];
   NSString *dateString = [dateFormatter stringFromDate:pickerDate];
   NSLog(@"this is check date:%@",dateString);
   //here dateString is a string variable which stores the value of the picker.
   [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

   dateFromString = [dateFormatter dateFromString:dateString];
   NSLog(@"Now complete date: %@",dateFromString);
   [dateFormatter release];

   //dateFromString is an nsdate variable where i storing the nsdate 
   //by converting the string dateString into date

   //dateFromString variable time and dateString variable time does not matches.

   return dateString;
}

然后我在我的另一个控制器中调用我的通知方法,我有我的保存按钮

-(IBAction)save{
  [self setNotification:timepicker.dateFromString message:@"message"];
}

timepicker是创建datepicker的类的对象。

如何使我的日期选择器选择时间与当前时间匹配,以便可以在适当的时间设置通知。

请帮我解决这个问题。谢谢

编辑:

我已添加通知代码以在appdelegate

中接收通知
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{ 

    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Alarm" message:notification.alertBody delegate:self cancelButtonTitle:nil otherButtonTitles:@"SnooZe",@"STOP",nil]; 
    [alert show]; 
    [alert release]; 
    [[UIApplication sharedApplication]cancelLocalNotification:notification]; 
}

设置通知这是代码

-(void)setNotification :(NSDate *)dat message:(NSString *)str{ 
    UILocalNotification *local=[[UILocalNotification alloc]init]; 
    [local setAlertBody:str]; 
    [local setFireDate:dat]; 
    [local setSoundName:UILocalNotificationDefaultSoundName]; 

    [[UIApplication sharedApplication] scheduleLocalNotification:local]; 
    [local release]; 
}

在保存按钮操作中调用此方法单击

2 个答案:

答案 0 :(得分:0)

如果要在选择器被触发时更改,请在选择器上更改目标的事件。

如果日期与当前日期不匹配,请更改日期格式以使其匹配。

答案 1 :(得分:0)

为什么要将日期转换为字符串,然后修改日期格式化程序(设置时区),然后将字符串转换回日期?为什么日期格式化程序的格式中没有日期格式组件?为什么不直接将选择器中的NSDate传递给您设置的通知消息?