gpt4 book ai didi

ios - 如何删除核心数据中的对象

转载 作者:行者123 更新时间:2023-11-28 20:04:23 26 4
gpt4 key购买 nike

我正在尝试了解核心数据的工作原理。所以我的核心数据中有 2 个实体:Voiture 和 Garage(是的,我是法国人 :))

我可以创建对象,但不能删除它们!我什么都试过了……能帮我一点忙就好了!

这是我的代码:

@interface dataBaseViewController ()

@property(strong,nonatomic) UIManagedDocument *document;
@property(strong,nonatomic) NSManagedObjectContext *context;

@end

@implementation dataBaseViewController

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a

[self initDocument];

self.context=self.document.managedObjectContext;

}


-(void) initDocument{



//find url
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory=[[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *documentName=@"MyDocument";
NSURL *url= [documentsDirectory URLByAppendingPathComponent:documentName];


//create / open the document
self.document = [[UIManagedDocument alloc] initWithFileURL:url] ;

if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {

[self.document openWithCompletionHandler:^(BOOL success) {
if (success) NSLog(@"doc ouvert");
if (!success) NSLog(@"couldn’t open document at %@", url);
}];

} else {

[self.document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) NSLog(@"document created");
if (!success) NSLog(@"couldn’t create document at %@", url);
}];
}
}



- (IBAction)ajouterVoiture:(id)sender {
Voiture *nouvelleVoiture =[NSEntityDescription insertNewObjectForEntityForName:@"Voiture" inManagedObjectContext:self.context];
nouvelleVoiture.marque=@"ferreri";

}
- (IBAction)nbVoitures:(id)sender {
NSError *error;
NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:@"Voiture"];

NSLog(@"nombre de voitures : %lu",[self.context countForFetchRequest:request error:&error]);
}


- (IBAction)delete:(id)sender {
[self.context deletedObjects];
NSError *error;
[self.context save:&error];
}


@end

最佳答案

获取托管对象后,您可以使用上下文提供的 deleteObject: 方法将其从托管对象上下文中删除。

NSManagedObject *someObject;

[context deleteObject:someObject];

在使用 save: 方法保存上下文之前,对象不会从磁盘上的底层持久存储中删除。

关于ios - 如何删除核心数据中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22578935/

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