我有3个文本字段 - 姓名,年龄,电话号码 每次我输入每个字段的值都将存储在核心数据
上此外,我想检查我的数据库中的任何重复,即
我试了很多.. 请帮助我
我的代码是
NSEntityDescription *entityDescc=[NSEntityDescription entityForName:@"Name" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entityDescc];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"sname like %@ ",self.nameTextField.text];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData=[self.managedObjectContext executeFetchRequest:request error:&error];
if (matchingData.count<=0) {
NSEntityDescription *entityDesc=[NSEntityDescription entityForName:@"Name" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newObject=[[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:self.managedObjectContext];
[newObject setValue:self.nameTextField.text forKey:@"sname"];
[newObject setValue:self.ageTextField.text forKey:@"age"];
NSError *error;
[self.managedObjectContext save:&error];
}
else{
int count=0;
for (record *obj in matchingData) {
NSEntityDescription *entityDescc=[NSEntityDescription entityForName:@"Name" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request=[[NSFetchRequest alloc]init];
[request setEntity:entityDescc];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"age like %@ ",self.ageTextField.text];
[request setPredicate:predicate];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData=[self.managedObjectContext executeFetchRequest:request error:&error];
if (matchingData.count<=0) {
NSLog(@"Entered");
NSEntityDescription *entityDesc=[NSEntityDescription entityForName:@"Name" inManagedObjectContext:self.managedObjectContext];
NSManagedObject *newObject=[[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:self.managedObjectContext];
[newObject setValue:self.ageTextField.text forKey:@"age"];
NSError *error;
[self.managedObjectContext save:&error];
}
++count;
}
}
不检查属性Age
答案 0 :(得分:0)
将所有三个细节保存在单个实体中。获取给定实体中的所有记录,不带任何谓词。为每条记录创建一个模型类。使用模型类列表执行业务逻辑。这将解决您的问题,并使您的应用程序表现更好。