开发者

CoreData Basics Help

EDIT: I have altered the NSPredicate as recommended so that my fetch code look like so. Having printed to the UITextView like开发者_如何学运维 this, when I press load it spits out the following:

<NSManagedObject: 0x1c7cf0>(entity: DatedText; id: 0x1420c0 <x - coredata://B52D4F88-0210-4AE2-9DA6-C05ED64FE389/DatedText/p12> ; data: <fault>)

So either its not getting any data data because it hasn't been saved/loaded correctly or I am trying to get the loaded result into a UITextView the incorrect way. Any ideas?

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);
        return nil;
    }
    NSString *object = [NSString stringWithFormat:@"%@",[fetchedObjs objectAtIndex:0]];
    noteTextView.text = object;

I have been having all sorts of problems working out how to use Core Data, so I have gone back to basics, new window based ipad project using core data.

I have added a view and some code which doesn't work, hehe. Im basically trying to save some text to a date, then when going back to that date, the text which was previously saved will be shown again.


There's a tutorial on iPhone developer site here. And there are several sample codes with Core Data as well. These should get you started.


I checked your project and aside from having to synthesize the CoreData properties, I also just noticed you were trying to assign an NSArray to your fetch predicate, but it actually expects an NSPredicate object. You should use this instead:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@)", datePicker.date];
[fetch setPredicate:pred];

If you want to set more than 1 predicate you should do that on your predicate string i.e.

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@) AND (dateSaved <= %@", datePicker.date, [NSDate date]];

Cheers, Rog


You most likely crashing because your ivar is managedObjectContext_ but you are using self.managedObjectContext. You also need to synthesize the core data ivars even if you provide a custom getter.


You're setting your NSFetchRequest's predicate to an NSArray, not an NSPredicate.

If you had posted the actual crash, it would probably say something like an unknown selector was sent to an instance of NSArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜