Core Data - Iterating through the attributes of a NSManagedObject

后端 未结 2 1730
傲寒
傲寒 2021-02-07 11:20

I am a noob at core data, so here goes.

I have a core data object, for example student.

The student has mane attributes, like name, age, dob, address, and so on.

2条回答
  •  长情又很酷
    2021-02-07 11:52

    If you are like me and are trying to solve this problem in Swift here is how I did it.

    SWIFT 3:

    let request:NSFetchRequest
    if #available(iOS 10.0, *){
        request = ENTITY_NAME.fetchRequest() as! NSFetchRequest
    }else{
        request = NSFetchRequest(entityName: "ENTITY_NAME")
    }
    
    do{
        let entities = try YOUR_MOC.fetch(request)
        for item in entities{
            for key in item.entity.attributesByName.keys{
                let value: Any? = item.value(forKey: key)
                print("\(key) = \(value)")
            }
        }
    }catch{
    
    }
    

    Swift 2:

       let request = NSFetchRequest(entityName: "ENTITY_NAME")
       do{
           let entities = try YOUR_MOC.executeFetchRequest(request) as! [YOUR_ENTITY]
           for item in entities{
               for key in item.entity.attributesByName.keys{
                   let value: AnyObject? = item.valueForKey(key)
                   print("\(key) = \(value)")
               }
    
           }
       }catch{
    
       }
    

    If you want to get relationship entities key/values as well then you should use propertiesByName instead of attributesByName like so:

    SWIFT 3:

    for key in item.entity.propertiesByName.keys{
        let value: Any? = item.value(forKey: key)
        print("\(key) = \(value)")
    }
    

    SWIFT 2:

    for key in item.entity.propertiesByName.keys{
        let value: AnyObject? = item.valueForKey(key)
        print("\(key) = \(value)")
    }
    

    Just remember to be careful with the value since it is an NSManagedObject.

提交回复
热议问题