BadmintonCat
BadmintonCat

Reputation: 9586

Core Data - Get managed object by URI

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 ...

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?

Upvotes: 1

Views: 1287

Answers (2)

BadmintonCat
BadmintonCat

Reputation: 9586

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

The above method works fine otherwise.

Upvotes: 0

Mundi
Mundi

Reputation: 80273

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

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

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

I have changed your variable names for readability.

Upvotes: 1

Related Questions