gpt4 book ai didi

ios - 在 iOS 中删除和更新核心数据中的数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:04 24 4
gpt4 key购买 nike

大家好,我是 iOS Core Data 的新手,我已经实现了 4 个文本字段,即姓名、年龄、公司、地址。现在,当用户输入数据时,我将数据保存在 Core Data 中。

NSManagedObjectContext *context =
[appDelegate managedObjectContext];

NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:@"Device"
inManagedObjectContext:context];
[newContact setValue: _name.text forKey:@"name"];
[newContact setValue: _address.text forKey:@"address"];
[newContact setValue: _age.text forKey:@"age"];
[newContact setValue:_company.text forKey:@"company

同样,我能够获取并显示这些文本字段中的数据。

AppDelegate *appDelegate = [[UIApplication sharedApplication] 委托(delegate)];

NSManagedObjectContext *context =
[appDelegate managedObjectContext];

NSEntityDescription *entityDesc =
[NSEntityDescription entityForName:@"Device"
inManagedObjectContext:context];

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

NSPredicate *pred =
[NSPredicate predicateWithFormat:@"(name = %@)",
_name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;

NSError *error;
NSArray *objects = [context executeFetchRequest:request
error:&error];matches = objects[0];

_address.text = [matches valueForKey:@"address"];
_age.text = [matches valueForKey:@"age"];
_company.text = [matches valueForKey:@"company"];

现在,当我想删除和更新特定用户的数据时,我无法获取数据。

如何删除数据并更新..?

我已经通过这个链接 http://www.appcoda.com/core-data-tutorial-update-delete/

提前致谢

最佳答案

您可以删除如下数据:

 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"entityname" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID like %@",userID];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];

NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *managedObject in items)
{
[context deleteObject:managedObject];
}

和更新:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"entityname" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID like %@",userID];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
YourEntityname *entity = arrResult[0];
entity.userID = @"2"
[appdelegate saveContext];

关于ios - 在 iOS 中删除和更新核心数据中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38458195/

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