Search code examples
objective-ccore-dataswiftnsmanagedobjectcontext

Core Data: Could not find member executeFetchRequest


Does anyone know why I'm getting the above error with the following code?

var moc:NSManagedObjectContext? = managedObjectContext!;
var req:NSFetchRequest = NSFetchRequest();
var ent:NSEntityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: moc);
req.entity = ent;
var err:NSError? = nil;
var result = moc!.executeFetchRequest(req, error: err);

I've checked another SO ticket with this error message but can't figure it out. result is inferred from moc!.executeFetchRequest (as NSArray), the method signature seems correct so why can't it find executeFetchRequest on the moc?


Solution

  • The error message is misleading. You have to pass the address of the error variable:

    var err:NSError? = nil
    var result = moc!.executeFetchRequest(req, error: &err)
    

    Also it seems unnecessary to me to define the local context variable as an optional, and you don't have to specify the variable types if it can be implied from the context. So your code could be simplified to

    let moc = managedObjectContext!
    let req = NSFetchRequest(entityName: entityName)
    var err:NSError? = nil
    let result = moc.executeFetchRequest(req, error: &err)