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

标签 ios iphone core-data uimanageddocument

我正在尝试了解核心数据的工作原理。 所以我的核心数据中有 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/

相关文章:

ios - iphone-如何在 ios 中不导航消息窗口的情况下发送 SMS [未重复]

ios - 是否可以快速从 CoreData 中获取数组?

ios - 添加到移动 Sprite 时,CCParticleSystemQuad 未被释放

ios - 如何使用搜索栏输入文本并过滤选择?

iphone - 在 iPhone 中检索文本文件时出现问题

ios - 核心数据 : Custom attribute accessor not accessed the first time NSManagedObject is loaded

ios - 使用 Swift CoreData 进行动态过滤

ios - 在表格 View 单元格中标记按钮

ios - 如何在swift中进行多重继承?

ios - 本地服务器上的 ApprtcDemo 在浏览器和 Android 之间工作,但在 iOS 上不工作