gpt4 book ai didi

ios - 有什么方法可以限制核心数据中的重复条目吗?

转载 作者:可可西里 更新时间:2023-11-01 03:40:04 25 4
gpt4 key购买 nike

我一直在尝试在核心数据中添加对象。所以,我希望它不应该允许核心数据存储中的重复条目。怎么做?这是我与保存数据相关的代码。

  -(IBAction)save:(id)sender
{

if([name.text isEqualToString:@""] && [address.text isEqualToString:@""] && [phone.text isEqualToString:@""])
{

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yo..!"
message:@"Data Not Saved"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *context = [appDelegate managedObjectContext];


NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:@"Contacts"
inManagedObjectContext:context];


[newContact setValue:name.text forKey:@"name"];
[newContact setValue:address.text forKey:@"address"];
[newContact setValue:phone.text forKey:@"phone"];


name.text = @"";
address.text = @"";
phone.text = @"";

NSError *error;
[context save:&error];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yo..!"
message:@"Data Saved"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];

NSLog(@"Object Saved\n");

}


}

最佳答案

由于没有可用的内置方法,您需要获取结果并检查结果是否包含您不想复制的对象。

这是代码片段:

-(void)checkForDuplicates
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Students"
inManagedObjectContext:managedObjectContext];

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"students"
ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];

NSError *Fetcherror;
NSMutableArray *mutableFetchResults = [[managedObjectContext
executeFetchRequest:request error:&Fetcherror] mutableCopy];

if (!mutableFetchResults) {
// error handling code.
}

if ([[mutableFetchResults valueForKey:@"users"]
containsObject:name.text]) {
//notify duplicates
return;
}
else
{
//write your code to add data
}
}

希望对您有所帮助!

关于ios - 有什么方法可以限制核心数据中的重复条目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15239407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com