这是数组的样子:
Optional([<CKRecordZone: 0x155f0dc0; zoneID=_defaultZone:__defaultOwner__, capabilities=(none)>, <CKRecordZone: 0x155e8370; zoneID=MedicalRecord:__defaultOwner__, capabilities=(Atomic,Sync,Share)>])
如您所见,我在此数组中有两个元素,一个包含 zoneID = _defaultZone ,另一个包含 zoneID = MedicalRecord 。我怎样才能获得zoneID
= MedicalRecord的元素?我尝试了以下但不起作用:
if let index = recordZone?.index(of: CKRecordZone(zoneName: "MedicalRecord")) {
print("Index is: \(index)")
self.sendHeartRate(id: (recordZone?[index].zoneID)!)
}
永远不会运行此if let
阻止因为index
始终为零......
提前致谢!
答案 0 :(得分:1)
if let
块中的索引始终为零,因为在此行中:
if let index = recordZone?.index(of: CKRecordZone(zoneName: "MedicalRecord")) {
CKRecordZone(zoneName...
是一个全新的对象,与数组中已存在的对象分开。它可能与您要检索的区域名称具有相同的区域名称(“MedicalRecord”),但它们仍然是两个不同的对象。 (见下文。)
我创建的演示代码:
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)!)")
}
正如您所看到的,第一个MedicalZone
(数组中的一个)与之后创建的后者MedicalZone
不同:
(lldb) po zone
<CKRecordZone: 0x6180000b06e0; zoneID=MedicalZone:__defaultOwner__, capabilities=(Atomic,Sync)>
(lldb) po tempZ
<CKRecordZone: 0x6180000b0800; zoneID=MedicalZone:__defaultOwner__, capabilities=(Atomic,Sync)>
答案 1 :(得分:0)
我可以通过以下方式来做到这一点!
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)
}
}