简体   繁体   中英

Retrieve object from fetch request Swift

I have a core data entity called "Device" with one attribute called "asset_tag" along with the following code:

var endArray: [Device] = []

var request = NSFetchRequest<NSFetchRequestResult>()
            request = Device.fetchRequest()
            request.returnsObjectsAsFaults = false

endArray = try context.fetch(request) as! [Device]

print (endArray)

this prints out the following:

[<Device: 0x608000092c00> (entity: Device; id: 0xd000000000140000 <x-coredata://22AC91EB-92B1-4E5B-A5A9-A5924E0ADD3E/Device/p5> ; data: {
    "asset_tag" = 26;
})]

All I want it to print out is ['26']

Try like this-:

func loadData(){
            let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

            do{
              endArray = try context.fetch(request) as! [Device]
                for data in 0..< endArray!.count{
                    if let value = endArray?[data].value(forKey: "Your Key") {
                        print(value)
                    }
                }
            }catch{

            }


        }

You get that because endArray is a [Device] , which means that each entry in it is a Device . When you print the array, what you get is the result of calling debugDescription on each entry in the array.

If you just want the integer values of the asset_tag property in an array, you can get that array using map :

let tagValues : [Int] = endArray.map { Int($0.asset_tag) }

This says that tagValues has type [Int] , and that you're assigning a value by using map to get one value for each entry in endArray . That value is found by looking up the value of asset_tag on each entry. The result is an array of Int corresponding to the asset_tag values.

First of all if you are using a NSManagedObject subclass use a specific fetch request to avoid the type cast. And NSFetchRequest is reference type. Declare the request as constant ( let ).

A fetch request returns always an array of the entity [NSManagedObject] . The junk is important. The object can contain many attributes and relationships.

To get an array of a specific attribute use the map function

var endArray = [Device]()

let request : NSFetchRequest<Device> = Device.fetchRequest()
request.returnsObjectsAsFaults = false

do {
    endArray = try context.fetch(request)
    let tagArray = endArray.map { $0.asset_tag }
    print(tagArray)
} catch { print(error) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM