繁体   English   中英

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

[英]how to delete objects in core data

我正在尝试了解核心数据如何工作。 所以我的核心数据中有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:方法保存上下文,否则不会从磁盘上的基础持久性存储中删除该对象。

强烈推荐Magical Record吊舱。 大大简化了样板核心数据操作。

[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
    MyEntity *entity = [MyEntity MR_createInContext:localContext];
    MyOtherEntity *otherEntity = [MyOtherEntity MR_findFirstByAttribute:@"id" withValue:12345];

    entity.attribute1 = @"Foo";
    entity.attribute2 = @"Bar";

    [otherEntity deleteInContext:localContext];
}];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM