所以我正在使用CoreData做申请表 首先,我要创造" Shop"具有唯一名称和一些属性。 在应用程序中,您可以编辑" Shop",然后我尝试通过" shopName"进行验证。避免创作另一个" Shop"同名。 我用这个:
-(BOOL)uniqueEntityExistsWithEnityName {
BOOL returnValue = NO;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Shop"];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"shopName = [cd] %@", _shopName.text];
NSSortDescriptor *shop = [[NSSortDescriptor alloc] initWithKey:@"shopName" ascending:YES];
[request setSortDescriptors: @[shop]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *matches = [self.managedObjectContext executeFetchRequest:request error:&error];
NSLog(@"request = %@",predicate);
if (!matches) {
NSLog(@"Error: Couldn't execute fetch request %@", error);
}
else if([matches count] > 1) {
NSString *existShop = [NSString stringWithFormat:@"Could Be Only One %@ Shop", _shopName.text];
UIAlertView *exist = [[UIAlertView alloc]initWithTitle:@"Shop Exists in Your Records"
message:existShop
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[exist show];
NSLog(@"Error: Have more than %lu records",
(unsigned long)[matches count]);
returnValue = YES;
}
else {
NSLog(@"%lu object in record", (unsigned long)[matches count]);
[self oldShopDelete];
[self checkShopPhoneNumber];
editShop.shopName = _shopName.text;
editShop.shopPhoneNumber = _shopPhoneNumber.text;
editShop.shopSecondPhoneNumber = _shopSecondPhoneNumber.text;
editShop.shopEmail = _shopEmail.text;
editShop.shopNote = _shopNoteView.text;
[super saveAndDissmiss];
returnValue = YES;
}
return returnValue;
}
使用该代码,您仍然有机会再保存一个已编辑的" Shop"同名。
但问题是 - 在此之后我无法制作[matches count] = 1
我将无法编辑该商店
也许有另一种方法可以进行此类验证?
答案 0 :(得分:1)
仅在首次实际设置名称或编辑名称时检查名称冲突。
您还可以将当前商店传递到谓词中以确保AND SELF != %@
,这样就不会与正在编辑但名称未更改的现有商店匹配。