核心数据 - 通过URI获取托管对象

时间:2022-09-01 14:31:13

I'm trying to fetch managed objects from Core Data by their URI. For this I found an Objective-C example of a method (http://www.cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html) and converted it to Swift ...

我正在尝试通过URI从Core Data中获取托管对象。为此,我找到了一个方法的Objective-C示例(http://www.cocoawithlove.com/2008/08/safely-fetching-nsmanagedobject-by-uri.html)并将其转换为Swift ...

func getManagedObjectWithURI(uri:NSURL) -> NSManagedObject?
{
    if let psc = persistentStoreCoordinator
    {
        let objID = psc.managedObjectIDForURIRepresentation(uri);
        if (objID != nil)
        {
            let obj:NSManagedObject = managedObjectContext!.objectWithID(objID!);

            if (!obj.fault)
            {
                return obj;
            }

            let prd = NSComparisonPredicate(leftExpression: .expressionForEvaluatedObject(), rightExpression: NSExpression(forConstantValue: obj), modifier: .DirectPredicateModifier, type: .EqualToPredicateOperatorType, options: .allZeros);

            let req = NSFetchRequest();
            req.entity = objID?.entity;
            req.predicate = prd;

            var results:[NSManagedObject] = managedObjectContext!.executeFetchRequest(req, error: nil) as! [NSManagedObject];

            if (!results.isEmpty)
            {
                return results.first;
            }
        }
    }

    return nil;
}

However the method always returns nil, i.e. the fetch request returns empty-handed and I don't know why. Up to the NSFetchRequest everything looks valid. Does anyone has an idea what could be wrong?

然而,该方法总是返回nil,即获取请求空手返回,我不知道为什么。直到NSFetchRequest一切看起来都有效。有没有人知道什么可能是错的?

2 个解决方案

#1


Check that the entity and the predicate contain the expected values.

检查实体和谓词是否包含预期值。

Another suggestion is to write your predicate with NSPredicate(format:) for clarity.

另一个建议是使用NSPredicate(格式:)编写谓词以保持清晰。

request.predicate = NSPredicate(format: "self = %@", object)

I have changed your variable names for readability.

为了便于阅读,我更改了变量名称。

#2


Solved the issue. It was actually related to another, deeper problem in my core data code explained here: Mac OSX - Core data isn't stored

解决了这个问题。它实际上与我在此解释的核心数据代码中的另一个更深层次的问题相关:Mac OSX - 未存储核心数据

The above method works fine otherwise.

否则上述方法可以正常工作。

#1


Check that the entity and the predicate contain the expected values.

检查实体和谓词是否包含预期值。

Another suggestion is to write your predicate with NSPredicate(format:) for clarity.

另一个建议是使用NSPredicate(格式:)编写谓词以保持清晰。

request.predicate = NSPredicate(format: "self = %@", object)

I have changed your variable names for readability.

为了便于阅读,我更改了变量名称。

#2


Solved the issue. It was actually related to another, deeper problem in my core data code explained here: Mac OSX - Core data isn't stored

解决了这个问题。它实际上与我在此解释的核心数据代码中的另一个更深层次的问题相关:Mac OSX - 未存储核心数据

The above method works fine otherwise.

否则上述方法可以正常工作。