1

I have data stored in Code Data with a table called Users. I am simply trying to pull the "FirstName" from the array of data returned but keep getting "nil" in my console.

let fetchRequest = NSFetchRequest(entityName:"Users")

let fetchedResults =

managedContext.executeFetchRequest(fetchRequest, error: &error) as? [Users]

    var arrayvalues=NSArray(array: fetchedResults!)

    if let results = managedObject?.executeFetchRequest(fetchedResults, error: nil) as? [Users] {
        let someObject = results[firstName]
    }

My user class looks like:

class Users: NSManagedObject {

@NSManaged var email: String
@NSManaged var firstName: String
@NSManaged var fLast: String
@NSManaged var fullName: String
@NSManaged var id: String
@NSManaged var isActive: String
@NSManaged var lastName: String
@NSManaged var lastupdated: String
@NSManaged var role: String
@NSManaged var uPass: String

}

I've been looking for ways to achieve this but cant seem to fetch any of the FirstNames...

1 Answer 1

1

Replace

if let results = managedObject?.executeFetchRequest(fetchedResults, error: nil) as? [Users] {
    let someObject = results[firstName]
}

By

var firstNames = [String]() // empty array to keep the firstNames
if let results = managedObject?.executeFetchRequest(fetchedResults, error: nil) as? [Users] {
    for user in results  {
        firstNames.append(user.firstName)
    }
}

My code snippet adds the firstName of every user in the firstNames array. You have to realise that someObject in your code is not a single User but an array of Users.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for this but im not trying to pull a single user im trying to pull an array of firstName's...
That's a minor addition, just edited the code to create an array of firstNames.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.