Core Data - Iterating through the attributes of a NSManagedObject

青春壹個敷衍的年華 提交于 2019-12-03 10:27:58

Here's a very simple way to iterate over an NSManagedObject:

NSEntityDescription *entity = [myManagedObject entity];
NSDictionary *attributes = [entity attributesByName];
for (NSString *attribute in attributes) {
    id value = [myManagedObject valueForKey: attribute];
    NSLog(@"attribute %@ = %@", attribute, value);
}

The clues for how to do this (plus lots more) comes from Ole Bergmann's blog: http://oleb.net/blog/2011/05/inspecting-core-data-attributes/

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<ENTITY_NAME>
if #available(iOS 10.0, *){
    request = ENTITY_NAME.fetchRequest() as! NSFetchRequest<ENTITY_NAME>
}else{
    request = NSFetchRequest<ENTITY_NAME>(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!