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

时间:2014-03-22 14:34:02

标签: 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

2 个答案:

答案 0 :(得分:3)

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

NSManagedObject *someObject;

[context deleteObject:someObject];

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

答案 1 :(得分:0)

高度推荐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];
}];