Search code examples
nsarrayswift2ios9xcode7

NSArray Return Error


How else can I return the items in the array? I'm having trouble with the returning items as it's saying that I have used it before initializing it.

class func fetchEntities(className:NSString, withPredicate predicate:NSPredicate?, managedObjectContext:NSManagedObjectContext)->NSArray {
    let fetchRequest: NSFetchRequest = NSFetchRequest()
    let entetyDescription: NSEntityDescription = NSEntityDescription.entityForName(className as String, inManagedObjectContext: managedObjectContext)!

    fetchRequest.entity = entetyDescription
    if (predicate != nil) {
        fetchRequest.predicate = predicate!
    }

    fetchRequest.returnsObjectsAsFaults = false
    let items:NSArray

    do {
        items = try managedObjectContext.executeFetchRequest(fetchRequest)
    }
    catch(let error as NSError) {
        NSLog(error.localizedDescription)
    }
    return items
}

Solution

  • You can define array of type ManagedObject and store result in it as below. I have declared an array named users which is of type ManagedObject User

    // Declare users array which stores objects of `User` class only.
    var users  = [<User>]()
    
    // Execute request and store result into array
    users = try managedObjectContext.executeFetchRequest(fetchRequest)
    
    // return stored array
    return users
    

    i hope this helps you.