Reputation: 780
Here is what the array looks like:
Optional([<CKRecordZone: 0x155f0dc0; zoneID=_defaultZone:__defaultOwner__, capabilities=(none)>, <CKRecordZone: 0x155e8370; zoneID=MedicalRecord:__defaultOwner__, capabilities=(Atomic,Sync,Share)>])
As you can see I have two elements in this array, one with the zoneID=_defaultZone and another one with the zoneID=MedicalRecord. How can I get only the element with the zoneID
= MedicalRecord? I tried the following but it isn't working:
if let index = recordZone?.index(of: CKRecordZone(zoneName: "MedicalRecord")) {
print("Index is: \(index)")
self.sendHeartRate(id: (recordZone?[index].zoneID)!)
}
It's never running this if let
block 'cause index
is always nil...
Thanks in advance!
Upvotes: 0
Views: 54
Reputation: 780
I could do it by doing the following!
let count = recordZones?.count
for item in recordZones!{
let zoneName = (item.value(forKey: "_zoneID") as! CKRecordZoneID).value(forKey: "_zoneName") as! String
print("zone name is: \(zoneName)")
if(zoneName == "MedicalRecord"){
self.sendHeartRate(id: item.zoneID, heartRate: heartRate)
}
}
Upvotes: 0
Reputation: 1990
The index in your if let
block is always nil because in this line:
if let index = recordZone?.index(of: CKRecordZone(zoneName: "MedicalRecord")) {
the CKRecordZone(zoneName...
is a completely new object, separate from the one that already exists in the array. It may have the same zone name as the one you are trying to retrieve ("MedicalRecord"), but nevertheless they are still two distinct objects. (See below.)
Demonstration code I created:
let zone = CKRecordZone(zoneName: "MedicalZone")
let defaultZone = CKRecordZone.default()
let zoneArray = [defaultZone, zone]
let idx = zoneArray.index(of: zone)
print("*** Zone index: \(idx)")
let z = zoneArray[idx!]
print("*** z: \(z)")
if let i = zoneArray.index(of: zone) {
print("*** Index is: \(i)")
print("*** id: \(zoneArray[i].zoneID)!)")
}
let tempZ = CKRecordZone(zoneName: "MedicalZone")
if let index = zoneArray.index(of: tempZ)) {
print("*** Index is: \(index)")
print("*** id: \(zoneArray[index].zoneID)!)")
}
As you can see, the first MedicalZone
, the one in the array, is different from the latter MedicalZone
, that was created afterwards:
(lldb) po zone
<CKRecordZone: 0x6180000b06e0; zoneID=MedicalZone:__defaultOwner__, capabilities=(Atomic,Sync)>
(lldb) po tempZ
<CKRecordZone: 0x6180000b0800; zoneID=MedicalZone:__defaultOwner__, capabilities=(Atomic,Sync)>
Upvotes: 1