我想删除属性name
中与值Test
匹配的实体object.setValue("Test", forKey: "markedCell")
中的条目。
例如,我将一个条目保存到核心数据中:"Test"
。现在我想知道条目markedCell
是否保存在属性var request:NSFetchRequest = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", "Test")
var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]
中以及它具有哪个indexPath。我尝试了以下一个:
"Test"
现在我知道条目"Test"
是否存在但是不知道它有哪个indexPath(如果我知道它有哪个indexPath,我只能删除一个条目?)。目前,我想删除条目""
(不要将其设置为"Test"
)。
我的CoreData模型:
我想从markedCell
删除cellForRowAtIndexPath
。
你们中的某些人是否知道如何在Swift中做到这一点?
创建单元格(//Get task
let context = self.fetchedResultsController.managedObjectContext
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
var taskString:NSString?
taskString = object.valueForKey("name") as? String
cell.textLabel!.text = object.valueForKey("name") as? String
println(object.valueForKey("name") as? String)
//Set accessory type
var request:NSFetchRequest = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", taskString!)
var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]
if (results.count > 0) {
//Element exists
cell.accessoryType = UITableViewCellAccessoryType.None
println("Cell isn't marked")
}
else {
//Doesn't exist
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
println("Cell is marked")
}
):
mount -o remount,rw -t yaffs2 /dev/block/mtdblock2 /system
崩溃:
我希望这张照片有助于更好地理解我的问题。图片的链接:https://www.dropbox.com/s/h5g4yeoedg0xjjv/Stackoverflow_Question.png?dl=0
答案 0 :(得分:4)
如果我知道哪个indexPath正确,我只能删除一个条目?
这是错误的。 Core Data对象没有索引路径。 (获取结果控制器管理Core Data对象以供显示 在表视图中然后你有索引路径,但这是完全的 这里无关紧要。)
只需获取要删除和删除的对象或对象即可 它们:
let request = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", "Test")
if let results = context.executeFetchRequest(request, error: nil) as? [NSManagedObject] {
// Delete _all_ objects:
for object in results {
context.deleteObject(object)
}
// Or delete first object:
if results.count > 0 {
context.deleteObject(results[0])
}
} else {
// ... fetch failed, report error
}
答案 1 :(得分:0)
对于Swift 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{
}
}