如何检查核心数据是否为空 [英] How to check if core data is empty
本文介绍了如何检查核心数据是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用Swift检查核心数据是否为空。我尝试了这种方法:
How do I check if core data is empty using Swift. I tried this method:
var people = [NSManagedObject]()
if people == nil {
}
但这会导致以下错误:
二进制运算符'=='不能应用于类型为[NSManagedObject]和nil的操作数
"binary operator '==' cannot be applied to operands of type [NSManagedObject] and nil"
推荐答案
要检查核心数据库是否为空,必须在服务器上输入 NSFetchRequest
您要检查的实体,并检查请求的结果是否为空。
To check if the Core Database is empty you have to make a NSFetchRequest
on the entity you want to check, and check if the results of the request are empty.
您可以使用以下功能进行检查:
func entityIsEmpty(entity: String) -> Bool
{
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context = NSManagedObjectContext()
var request = NSFetchRequest(entityName: entity)
var error = NSErrorPointer()
var results:NSArray? = self.context.executeFetchRequest(request, error: error)
if let res = results
{
if res.count == 0
{
return true
}
else
{
return false
}
}
else
{
println("Error: \(error.debugDescription)")
return true
}
}
或更短或更短的解决方案:(使用 .countForFetchRequest
)
Or simplier and shorter solution: (using .countForFetchRequest
)
func entityIsEmpty(entity: String) -> Bool
{
var appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var context = NSManagedObjectContext()
var request = NSFetchRequest(entityName: entity)
var error = NSErrorPointer()
var results:NSArray? = self.context.executeFetchRequest(request, error: error)
var count = context.countForFetchRequest(request, error: error)
if error != nil
{
println("Error: \(error.debugDescription)")
return true
}
else
{
if count == 0
{
return true
}
else
{
return false
}
}
}
这篇关于如何检查核心数据是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文