2015-06-29 89 views
0

我有Core Data與五個對象。它有四個String和一個NSDataUIImage)。我將它們保存在Core Data。然後在UIViewController加載,我想從核心數據中刪除它們,我得到了不同的錯誤。我嘗試了不同的方法,但它並沒有幫助我。我如何刪除這些數據?如何從Swift中的核心數據中刪除幾個不同的數據?

var name: String! 
var text: String! 
var image: UIImage! 
var url: String! 
var data: String! 

    func deleteAll() { 
    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) 
    var managedObjectContext: NSManagedObjectContext = appDel.managedObjectContext! 
    var coreDataName: NSManagedObject = (name as AnyObject?) as! NSManagedObject 
    var coreDataImage: NSManagedObject = (image as AnyObject?) as! NSManagedObject 
    var coreDataText: NSManagedObject = (text as AnyObject?) as! NSManagedObject 
    var coreDataData: NSManagedObject = (data as AnyObject?) as! NSManagedObject 
    var coreDataURL: NSManagedObject = (url as AnyObject?) as! NSManagedObject 

    managedObjectContext.deleteObject(coreDataName) 
    managedObjectContext.deleteObject(coreDataImage) 
    managedObjectContext.deleteObject(coreDataText) 
    managedObjectContext.deleteObject(coreDataData) 
    managedObjectContext.deleteObject(coreDataURL) 
    managedObjectContext.save(nil) 

    buttonDelete.enabled = false 
    buttonShare.enabled = false 
} 

} 

Core Data文件

import Foundation 
import CoreData 

@objc(News) 

    class News: NSManagedObject { 

     @NSManaged var dateNewsCoreDataString: String 
     @NSManaged var imageNewsCoreData: NSData // NSData 
     @NSManaged var nameNewsCoreData: String 
     @NSManaged var textNewsCoreData: String 
     @NSManaged var urlNewsCoreData: String 

    } 

回答

0

我改變了我的代碼,它爲我工作。

var detailObject: AnyObject? // It's data from FavoriteTableViewController 

    func deleteAll() { 
     var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate) 
     var managedObjectContext: NSManagedObjectContext = appDel.managedObjectContext! 

     var dataDelete = detailObject as! NSManagedObject 

     managedObjectContext.deleteObject(dataDelete) 
     managedObjectContext.save(nil) 

     managedObjectContext.save(nil) 
     buttonDelete.enabled = false 
     buttonShare.enabled = false 
    } 
相關問題