簡體   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