Ozvengrad
Ozvengrad

Reputation: 302

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
}

Upvotes: 0

Views: 97

Answers (2)

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

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.

Upvotes: 1

l00phole
l00phole

Reputation: 632

You should be returning NSArray? (i.e. nullable) as it can be nul if an exception is thrown:

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

Upvotes: 1

Related Questions