简体   繁体   中英

coredata get element of the array

I'm using CoreData in my application and I have two entities: Building and Phone which are connected using one-to-many relation.

I need to set the number property from the Phone entity to my textView.text field in the table view cell . I use the following code to achieve this (it's simplified for demonstration purposes):

let a = b.value(forKeyPath: "buildingPhones.number")

We can see from the output below that a variable now hows values of two phone numbers: Printing description of a: ▿ Optional<Any> ▿ some : 2 elements - 0 : +7 7162 40 15 69 - 1 : +7 7162 25 75 39

How can I access the first number in this array - +7 7162 40 15 69 ?

PS I'm pretty desperate now because I have tried litterely every found method, but still cannot do this. I have tried to access elements like in array, using object(at: 0) method and many-many others. Moreover, when I try to cast a to any type ( String or Array or NSArray or NSMutableArray it alwats returns nil .

What am I doing wrong?

You have to downcast the result of value(forKeyPath to the actual type [String] .

The save way to get the first number is

if let a = b.value(forKeyPath: "buildingPhones.number") as? [String],
   let firstNumber = a.first {
   print(firstNumber)
}

Be aware that the type of a one-to-many relationship is (unordered) Set . It's not guaranteed the the order of the array is always the same.

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