当我试图在我的核心数据模型上运行countForFetchRequest()时,我遇到了Swift抛出异常的问题。我有一个变通方法,但它很可怕,我希望有更好的方法。
以下是数据模型的相关部分:

下面是抛出异常的代码:
// Returns true if at least one object of type entityName with the value queryValue in the attribute
// attributeName exists in context context.
func objectWithAttrValueExists (attributeName: String, queryValue: AnyObject, entityName: NSString, context: NSManagedObjectContext) -> Bool {
    let allEntities = context.persistentStoreCoordinator.managedObjectModel.entitiesByName
    // Some debugging print statements to see what NSEntityDescriptions exist.
    for key in allEntities.keys {
        println(key as String)
    }
    var request = NSFetchRequest(entityName: entityName)
    let attributeFilter = NSPredicate(format: "%K == %@", argumentArray: [attributeName, queryValue])
    request.predicate = attributeFilter
    var error = AutoreleasingUnsafeMutablePointer<NSError?>()
    let count = context.countForFetchRequest(request, error: error) // <- Exception here.
    if count <= 0 {
        return false
    } else {
        return true
    }
}您可以看到,我在其中有一些调试print语句;它们的输出是:
FixtureParameterType
FixtureParameterCategory
Fixture
FixtureParameter然后抛出的异常是:NSFetchRequest could not locate an NSEntityDescription for entity name 'Fixture' (但是'Fixture‘在上面的打印语句中被打印出来了)。
下面是一个可怕的变通方法:我从NSEntityDescriptions的字典中获取键,遍历它们,然后手动将相关的NSEntityDescription分配给NSFetchRequest。我确实发现了这一点,所以thread建议使用NSString而不是String,但这并没有区别;无论哪种方式,我都会得到相同的异常。
func objectWithAttrValueExists (attributeName: String, queryValue: AnyObject, entityName: String, context: NSManagedObjectContext) -> Bool {
    let allEntities = context.persistentStoreCoordinator.managedObjectModel.entitiesByName
    for key in allEntities.keys {
        println(key as String)
    }
    // I would expect this to work, but it doesn't.
    //var request = NSFetchRequest(entityName: entityName)
    // This works but is horrible.
    var request = NSFetchRequest()
    for key in allEntities.keys {
        let strkey = key as String
        if strkey == entityName {
            request.entity = allEntities[key] as NSEntityDescription
        }
    }
    let attributeFilter = NSPredicate(format: "%K == %@", argumentArray: [attributeName, queryValue])
    request.predicate = attributeFilter
    var error = AutoreleasingUnsafeMutablePointer<NSError?>()
    let count = context.countForFetchRequest(request, error: error) // <- Works!
    if count <= 0 {
        return false
    } else {
        return true
    }我尝试这样做是因为我注意到allEntities中的值是_PFEncodedString的实例,我认为它可能会搞乱字典散列。我的变通方法让我认为这是正确的,但如果这是真的,那么我不知道其他人是如何让核心数据在Swift中工作的。
这快把我逼疯了--任何感谢的帮助。
发布于 2014-08-11 13:27:53
虽然已经提到使用NSString作为实体名称,但还是要再说一遍。
我也遇到了同样的问题,并通过
NSFetchRequest(entityName: entityName as NSString)此错误仅发生在设备上,而不是在模拟器中。
https://stackoverflow.com/questions/25235582
复制相似问题