Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get specific NSManagedObject from entity (core data)

I have an entity in my "ProjName.xcdatamodel" with the name "Questions". In this entity I have 5 attributes ("icehockey","volleyball","soccer",...), each with type transformable. Each row (attribute) will be filled with a NSMutableArray. What I want to do is to get the value of a specific attribute in this entity. This is my code:

func readQuestionsFromCore(sport:NSString) -> NSMutableArray {
    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var request = NSFetchRequest(entityName: "Questions")
    request.returnsObjectsAsFaults = false
    var results: NSArray = context.executeFetchRequest(request, error: nil)!
    var qArr:NSMutableArray!
    if results.count > 0 {
        var res = results[0] as NSManagedObject
        qArr = res.valueForKey("\(sport)") as NSMutableArray
        return qArr
    } else {
        qArr = []
        return qArr
    }
}

This will ofcourse not work since I take out the first index of the results from the database (results[0] as NSManagedObject) and thus it will crash if that element is not the same as the valueForKey I'm looking for.

How do I get the one result row that I'm looking for? I.e. "soccer", or at least can I somehow loop through the results and compare the keys of each result row so it doesn't crash when I try with the wrong key? Like something like this:

for (res) in results as NSManagedObject {
   if(res.key == "soccer") {
      qArr = res.valueForKey("soccer") as NSMutableArray
      return qArr
   }
}

I hope I'm clear in my explanation!

like image 550
user2099024 Avatar asked Jun 12 '15 07:06

user2099024


People also ask

How do I get NSManagedObject?

Still inside the Core Data editor, go to the Editor menu and choose Create NSManagedObject Subclass. Make sure your data model is selected then click Next. Make sure the Commit entity is checked then click Next again.

How can you retrieve data from Core Data?

Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.

What class would you use to filter fetched results from Core Data?

Core Data fetch requests can use predicates in SwiftUI just like they can with UIKit, all by providing a predicate property to your @FetchRequest property wrapper. If you followed my Core Data and SwiftUI set up instructions, you've already injected your managed object context into the SwiftUI environment.

Can we have multiple managed object context in Core Data?

Most apps need just a single managed object context. The default configuration in most Core Data apps is a single managed object context associated with the main queue. Multiple managed object contexts make your apps harder to debug; it's not something you'd use in every app, in every situation.


2 Answers

the valueForKey method returns an optional, you can use if let as below

if let questionsArr = res.valueForKey("\(sport)") as? NSMutableArray {
    return questionsArr
} else {
    return []
}

This works in Xcode 6.3.2, but looks like you are using older one. If so update to latest one.

like image 158
Tejesh Alimilli Avatar answered Sep 20 '22 16:09

Tejesh Alimilli


I'm not sure I clearly understand what you are trying to achieve. But using next function(that using KVC) you can get a list of class properties and than check if the one you need is there:

func getPropertyList(#classToInspect: AnyObject.Type) -> [String]
{
    var count : UInt32 = 0
    let properties : UnsafeMutablePointer <objc_property_t> = class_copyPropertyList(classToInspect, &count)
    var propertyNames : [String] = []
    let intCount = Int(count)
    for var i = 0; i < intCount; i++ {
        let property : objc_property_t = properties[i]
        let propertyName = NSString(UTF8String: property_getName(property))!
        propertyNames.append(propertyName as String)
    }
    free(properties)
    println(propertyNames)

    return propertyNames
}
like image 42
Vitalii Boiarskyi Avatar answered Sep 21 '22 16:09

Vitalii Boiarskyi