Swift - 自定义对象找到 nil,即使 objectId 是准确的


        let parent = path[row-1]
        let child = path[row]
        let indexOfChild = matrix[parent.objectId!]!.index(of: child)
        print("indexOfChild = (indexOfChild)")
        print("keyValuePair = (matrix[parent.objectId!]!)")
        print("child = (child)")
        let indexAfter =  matrix[parent.objectId!]!.index(after: indexOfChild!)

结果,我将此信息打印在控制台中。

如您所见,"child"(这是带有 argumentText 的参数对象:"example"(存在于 keyValuePair 中(它们具有相同的 objectId(。然而,它在keyValuePair中的索引在控制台中显示为零。显然,仅仅是区别:"child"旁边有"0x608000333f60">,而keyValuePair中的第二个参数对象有"0x600000321a40"。

我不知道这些的目的是什么以及如何计算它们,但在我看来,索引为零,因为这些代码彼此不同

我一直在尝试修复它太久了。有人可以帮我度过难关吗?


indexOfChild = nil
keyValuePair = [<Argument: 0x608000334e60, objectId: IG9ekqMRw9, localId: (null)> {
    ACL = "<PFACL: 0x60800042f200>";
    argumentText = "the only thing is I can't get over how I feel when it ";
    creatorId = hWRXoRvnYd;
    level = 4;
    parentId = j7GkpwUKsm;
    reach = 0;
    threadId = Dtq632QYJ2;
}, <Argument: 0x600000321a40, objectId: 56AsB1juNP, localId: (null)> {
    ACL = "<PFACL: 0x600000235440>";
    argumentText = "example ";
    creatorId = hWRXoRvnYd;
    level = 4;
    parentId = j7GkpwUKsm;
    reach = 0;
    threadId = Dtq632QYJ2;
}]
child = <Argument: 0x608000333f60, objectId: 56AsB1juNP, localId: (null)> {
    ACL = "<PFACL: 0x608000235540>";
    argumentText = "example ";
    creatorId = hWRXoRvnYd;
    level = 4;
    parentId = j7GkpwUKsm;
    reach = 0;
    threadId = Dtq632QYJ2;
}
fatal error: unexpectedly found nil while unwrapping an Optional value


0x608000333f600x600000321a40 值是相关变量的内存地址位置。由于地址位置不同,我相信两个子实例被视为两个单独的值,并且可能不会匹配。这可能是您遇到的问题。

最好

通过唯一 ID 值检查子实例的父实例,以便可以正确匹配父数组中的子实例。这有意义吗?

您可以通过以下方式找到子项的索引:

var index = -1
var found = false
for chld in matrix[parent.objectId!]! {
    index = index + 1
    if chld.objectId == child.objectId {
        found = true
        break
    }
}
if found {
    // The index value at this point is the index for the child
}

您也可以简单地过滤子数组,以在父数组中找到与child变量具有相同 objectId 的子数组,然后从子数组中找到索引,如下所示:

let chld = matrix[parent.objectId!]!.filter{ $0.objectId == child.objectId }.first
let indexOfChild = matrix[parent.objectId!]!.index(of: chld)

相关内容

  • 没有找到相关文章

最新更新