2011-06-29 64 views
23

我在我的應用程序中使用核心數據,並且在從核心數據存儲中刪除某些行或條目時我感到困惑。我插入一些產品到存儲像這樣:從Core-Data中刪除特定的條目/行

NSManagedObject *Product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:context]; 
[Product setValue:[NSNumber numberWithFloat:id] forKey:@"pid"]; 
[Product setValue:[NSNumber numberWithFloat:quantity] forKey:@"pquantity"]; 

這適用於插入。但是,在後面的應用程序中,我想刪除條目,例如,pid是53.我將如何去除僅此行/條目?等效的SQL將如下所示:

DELETE from Product WHERE pid = '53' 

我非常感謝一些示例代碼,因爲我似乎無法弄清楚這一點。

感謝您的任何幫助。

回答

6

請記住將核心數據視爲圖形而不是數據庫,因此行的概念不適用。相反,你想從圖中刪除一個特定的對象。

您使用insertNewObjectForEntityForName:inManagedObjectContext:來插入它。使用deleteObject:來刪除它,如:

[aContext deleteObject:aManagedObject];

在你的情況,

[context deleteObject:Product];

好運

看到蘋果的explanation here

注意:當你刪除,取決於你的計劃,這可能有不同的含義秒。例如,它可以刪除Core Data對象圖的子路徑下方的所有內容。確保在設計架構時應該認真思考應該如何工作。如果你正確設置它,這對你來說可能是一個巨大的優勢。

+0

已共享豐富的知識.. –

42

由於@Nektarios說,你在這裏處理對象,所以你想找到一個具有特定屬性值的對象。你用提取請求和謂詞。

NSNumber *soughtPid=[NSNumber numberWithInt:53]; 
    NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Product" inManagedObjectContext:context]; 
    NSFetchRequest *fetch=[[NSFetchRequest alloc] init]; 
    [fetch setEntity:productEntity]; 
    NSPredicate *p=[NSPredicate predicateWithFormat:@"pid == %@", soughtPid]; 
    [fetch setPredicate:p]; 
    //... add sorts if you want them 
    NSError *fetchError; 
    NSArray *fetchedProducts=[self.moc executeFetchRequest:fetch error:&fetchError]; 
    // handle error 

fetchedProducts陣列將包含實體Productpid屬性等於soughtPid的所有對象。請注意,謂詞與SQL中的where子句在邏輯上完成相同的功能。

一旦你的對象,你只是告訴背景下將其刪除:

for (NSManagedObject *product in fetchedProducts) { 
    [context deleteObject:product]; 
    } 

當您下一次保存的情況下,對象的數據將持久性存儲文件被刪除。

+0

我按照我的要求修改一些代碼,但是這個代碼對我的作品的感謝@TechZen – MahboobiOSDeveloper

+0

優秀作業U做了..它工作正常 –

+0

你能用swift編寫代碼嗎? – amish

2

使用本

Entity *entity = (Entity *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:managedObjectContext]; 
[entity setTimeStamp:[NSDate date]]; 
NSError *error; 
if ([managedObjectContext save:&error]) { 

} 
[eventArray delete:<#(id)sender#>]; 

[self.tableView reloadData]; 
5

使用此方法:

+ (void)Deletebeer:(NSString*)m_Beerid 
{ 
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
    NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

    NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Beers" inManagedObjectContext:context]; 
    NSFetchRequest *fetch=[[NSFetchRequest alloc] init]; 
    [fetch setEntity:productEntity]; 
    NSPredicate *p=[NSPredicate predicateWithFormat:@"m_Beerid == %@", m_Beerid]; 
    [fetch setPredicate:p]; 
    //... add sorts if you want them 
    NSError *fetchError; 
    NSError *error; 
    NSArray *fetchedProducts=[context executeFetchRequest:fetch error:&fetchError]; 
    for (NSManagedObject *product in fetchedProducts) { 
     [context deleteObject:product]; 
    } 
    [context save:&error]; 
} 
0

很簡單,其中DatabaseInfo是我的實體,其中文件名是屬性的名稱

CoreAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 

NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context]; 

NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:entityDesc]; 

NSPredicate *pred= [NSPredicate predicateWithFormat:@"(filename = %@)", @"Thankyou"]; 

[request setPredicate:pred]; 
NSManagedObject *matches = nil; 

NSError *error; 
NSArray *objects = [context executeFetchRequest:request error:&error]; 

if([objects count] == 0) 
{ 
    [email protected]"No Match Found"; 
} 
else{ 
    matches = objects[0]; 

    [context deleteObject:matches]  

} 
11

像sqlite的的「從tableName WHERE條件中刪除「,則沒有單個步驟可從CoreD中刪除MULTIPLE對象ATA。

CoreData,首先你要獲取必須被刪除,使用NSFetchRequestNSPredicate

NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"EntityName"]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"propertyName == %@", value]; 
[request setPredicate:predicate]; 

NSError *error = nil; 
NSManagedObjectContext *managedObjectContext;//Get your ManagedObjectContext; 
NSArray *result = [managedObjectContext executeFetchRequest:request error:&error]; 

然後對象,則應迭代通過每一個NSManagedObject並從您NSManagedObjectContext調用deleteObject:

if (!error && result.count > 0) { 
    for(NSManagedObject *managedObject in result){ 
     [managedObjectContext deleteObject:managedObject]; 
    } 

    //Save context to write to store 
    [managedObjectContext save:nil]; 
} 
+0

是的,這是完美的。 – ravinder521986

1

我一直在用UITableView滑動刪除幾天,最終我完成了事情。

tableview由來自核心數據對象的數據填充。代表方法已用於:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSectin:(NSInteger)section** 
{ 
    reture [_arrData count]; 
} 

-(NSInteger)numberOfSectionInTablesView:(UITableView *)tableView 
{ 
    return 1; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellID = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; 
    if(cell == nil){ 
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStleDefault reuseIdentifier:cellID]; 
    } 
    cell.textLable.text = [_arrData objectAtIndex:indexPath.row]; 
    return cell; 
} 

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{ 
    return YES; 
} 

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    UITableViewRowAction *delete = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"Delete" handler:^(UITableViewRowAction *action,NSIndexPath *indexPath){ 


     //**************load address ************** 
     NSError *error; 

     AppDelegate *sharedDelegate = [AppDelegate appDelegate]; 
     NSManagedObjectContext *context = [sharedDelegate managedObjectContext]; 

     NSEntityDescription *entity = [NSEntityDescription entityForName:@"data" inManagedObjectContext:context]; 

     NSFetchRequest *fetchReuqets = [[NSFetchRequest alloc] init]; 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lat == %@", [_arrLat objectAtIndex:indexPath.row]]; 
     [fetchReuqets setPredicate:predicate]; 

     NSLog(@"delete %@",[_arrLat objectAtIndex:indexPath.row]); 

     [fetchReuqets setEntity:entity]; 
     NSArray *fetchedObjects = [context executeFetchRequest:fetchReuqets error:&error]; 
     NSLog(@"number of filtered objects=%ld",fetchedObjects.count); 
     if(!error && fetchedObjects.count>0){ 
      for (NSManagedObject *addr in fetchedObjects){ 
       [context deleteObject:addr]; 
       NSLog(@"delete addr %@",addr); 
      } 
      [context save:&error]; 
     } 
     //***************core data************************** 
     [_arrData removeObjectAtIndex:indexPath.row]; 
     [tableView reloadData]; 

    }]; 
    delete.backgroundColor = [UIColor redColor]; 
    return @[delete]; 
} 

希望可以幫助別人。

0

在斯威夫特3:

  if let dataAppDelegatde = UIApplication.shared.delegate as? AppDelegate { 


       let mngdCntxt = dataAppDelegatde.persistentContainer.viewContext 

       let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCart") 

       let predicate = NSPredicate(format: "itemId = %i", Int(currentItemID)!) 
       print(currentItemID) 

       fetchRequest.predicate = predicate 
       do{ 
        let result = try mngdCntxt.fetch(fetchRequest) 

        print(result.count) 

        if result.count > 0{ 
         for object in result { 
          print(object) 
          mngdCntxt.delete(object as! NSManagedObject) 
         } 
        } 
       }catch{ 

       } 
      } 
+0

此代碼不會刪除該行,而是會使'currentItemId' = 0。我正在搜索刪除該行。 – amish