我正在尝试将产品存储在sqlite中。当我为数据库实体设置值时,我存储了正确的值。
但问题是我检查产品是否已经在数据库中,然后它不应该再次添加相同的产品。但是下次它在数据库中存储NULL值。
虽然我没有打电话给[addToFav setValue:@"我的价值"];
只需检查循环。当我的循环运行时,它不会进入第一个条件,我在那里制作计数器if(count == 0)
我不知道它存储NULL值的位置。虽然我没有在任何其他地方称呼它。那么它如何在数据库中存储NULL值?
- (IBAction)buttonAddToFavourite:(id)sender {
int count = 0;
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSManagedObject *addToFav = [NSEntityDescription insertNewObjectForEntityForName:@"Favourite" inManagedObjectContext:context];
NSString *dish = [results objectForKey:@"id"];
fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Favourite" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSString *id1 = [info valueForKey:@"dishid"];
if ([id1 isEqualToString:dish]) {
count = count +1;
}
}
if (count == 0) {
[addToFav setValue:[results objectForKey:@"id"] forKey:@"dishid"];
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:@"sucess"]
message:@"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else if (count > 0){
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:@"warning"]
message:@"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
答案 0 :(得分:1)
- (IBAction)buttonAddToFavourite:(id)sender {
NSError *error = nil;
NSString *dishId = results[@"id"];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Favourite"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"dishid == %@", dishId]];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count) {
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:@"warning"]
message:@"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else {
Favourite *obj = [NSEntityDescription insertNewObjectForEntityForName:@"Favourite" inManagedObjectContext:self.managedObjectContext];
obj.dishid = dishId;
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:@"sucess"]
message:@"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
}