DatePicker Stopping CoreData Work

2019-02-21 04:58发布

问题:

I have an app which saves text and the date from a UIDatePicker and then shows that note if you got back into that date in the UIDatePicker.

Its works great! Only I have found that setting the UIDatePicker date to today stops CoreData working!

Its only when I run this setDate line does it stop core data from working. The app runs fine without crashing, it just doesn't save any data. If I comment that line out, its works a charm. But I need to have the UIDatePicker on today when the app loads.

I use this when the application starts:

NSDate *now = [[NSDate alloc] init];
[datePicker setDate:now];

This to fetch the note:

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
        NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
        [fetch setEntity:testEntity];
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
        [fetch setPredicate:pred];

        NSError *fetchError = nil;
        NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
        if (fetchError != nil) {
            NSLog(@"fetchError = %@, details = %@",fetchError,fetchError.userInfo);
        }
        noteTextView.text = [[fetchedObjs objectAtIndex:0] valueForKey:@"savedText"];

And this to save the note:

NSManagedObject *newDatedText;
    newDatedText = [NSEntityDescription insertNewObjectForEntityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
    [newDatedText setValue:noteTextView.text forKey:@"savedText"];
    [newDatedText setValue:datePicker.date forKey:@"dateSaved"];

    NSError *saveError = nil;
    [self.managedObjectContext save:&saveError];
    if (saveError != nil) {
        NSLog(@"[%@ saveContext] Error saving context: Error = %@, details = %@",[self class], saveError,saveError.userInfo);
    }

回答1:

Remember NSDate saves not only DD/MM/YYYY but also HH:MM:SS.

At a guess I think when you pick a DD/MM/YYYY from the picker, it saves with a default time of 0:00:00 but in the case above when you set the picker date to now you are actually manipulating the HH:MM:SS to something else (even though you don't see it manually).

To illustrate what I'm trying to say, when you fetch is with a predicate of (dateSaved == picker.date) it is looking for a date in the format DD/MM/YYYY 00:00:00 and for arguments sake you may have saved it on DD/MM/YYYY 09:00:01.

You will need to do some formatting of your NSDate attribute if you want this to work.



回答2:

Datepicker is by default set to todays date only. You don't need to do it manually.