开发者

CoreData - fetch does not find objects

I'm kind of newbie on coredata, and i'开发者_运维技巧m building a simples database, with the result of an xml.

I'm testing to see if the record exists, and if not, add a new one, and then save, but when i do that again, e keeps saving, instead of finding the record.

This class method is called twice (2 records from the xml) and then i save in the mail class. ActivityID is a NSNumber.

What am i doing wrong?

Code:

+(CompanyActivity *)createActivityWithInfoFromServer:(NSDictionary *)activityDictFromArray  inManagedObjectContext:(NSManagedObjectContext *)context {

     CompanyActivity *companyActivity = nil;

     NSFetchRequest *request = [[NSFetchRequest alloc] init];
     request.entity = [NSEntityDescription entityForName:@"CompanyActivity" inManagedObjectContext:context];
     request.predicate = [NSPredicate predicateWithFormat:@"ActivityID == %@", [activityDictFromArray objectForKey:@"ActivityID"]];

     NSError *error = nil;
     companyActivity = [[context executeFetchRequest:request error:&error] lastObject];

     NSLog(@"activity: %@", companyActivity);

     if (!error && !companyActivity) {
          companyActivity = [NSEntityDescription insertNewObjectForEntityForName:@"CompanyActivity" inManagedObjectContext:context];
          companyActivity.ActivityID = [NSNumber numberWithInt:[[activityDictFromArray objectForKey:@"ActivityID"] integerValue]];
          companyActivity.ActivityDescription_PT = [activityDictFromArray objectForKey:@"ActivityDescription_PT"];
          companyActivity.ActivityDescription_EN = [activityDictFromArray objectForKey:@"ActivityDescription_EN"];
          companyActivity.DateChangedStamp = [NSDate date];
     }
     else
          NSLog(@"no Activity created. Errors: %@", error);

     return companyActivity;
}


The problem was in NSNumber. It kept saving records into the database, but did never find them. I've changed the type op data to NSString, for now.

Thanks,

RL


First things first, you're leaking request. Second, you should do some basic debugging to find the problem. Set some breakpoints and inspect your fetch to ensure that the activity id you're inserting into your fetch is a valid value. Make sure you're also filling out the object you create later properly with correct values. See how all that goes and if your problem has not been resolved, add more information to the question with your progress.


It doesn't appear that you're ever actually saving your new objects after you create them. Try adding the following code to your object creation block:

[context save:&error];
if(error) {
    NSLog(@"error saving entities: %@", error);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜