简体   繁体   中英

How can I save and display date picker value in detail text label using core data?

I have a simple reminder app using core data, with 2 entities, one for 'details' of the reminder and one for the 'date' of the reminder. The user adds a reminder and picks a date and that is then stored in a table view of all of their reminders.

I have the 'details' entity value saving correctly from the text field into the label of the table view but I can't seem to get the date to save from the date picker and into the detail text label of the table view.

In the EnterReminderViewController.m:

-(void)insertReminderDetails {

CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
ReminderEntry *entry = [NSEntityDescription insertNewObjectForEntityForName:@"ReminderEntry" inManagedObjectContext:coreDataStack.managedObjectContext];

entry.details = self.reminderTextField.text;
entry.date =  self.datePicker;


[coreDataStack saveContext];

}

And in UpcomingRemindersTableViewController.m:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:   (NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView    dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

ReminderEntry *entry = [self.fetchedResultsController objectAtIndexPath:indexPath];

cell.textLabel.text = entry.details;

 cell.detailTextLabel.text = entry.date;

return cell;

}

Do I need to convert the value to a string for this to work? Also, do I need to create a separate fetch request for the date?

In your first code snippet, your entry.date property appears to be a Core Data "date" attribute, which is equivalent to an NSDate in code. You're attempting to assign a UIDatePicker to it. That's incorrect, because UIDatePicker is a UI control that lets the user select a date, it's not a date in itself. You need to ask the date picker for its current date value-- probably self.datePicker.date in your code.

In your second code snippet, you appear to be assigning entry.date to a UILabel text attribute. That's also incompatible, because dates are not strings. A simple fix would be to use entry.date.description , but that will use GMT rather than local time. To get more control over converting a date to a string, look into NSDateFormatter .

您可以将属性值设置为要转换的日期,然后将日期选择器日期保存为init。我们必须将日期选择器日期作为NS Date而不是核心日期中的字符串。希望它将对您有所帮助。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM