gpt4 book ai didi

swift - 为什么下面的代码会导致无限递归?

转载 作者:搜寻专家 更新时间:2023-10-31 22:52:40 25 4
gpt4 key购买 nike

class TestClass : NSObject {

var definitions: NSSet = NSSet()

func addDefinitionsObject(value: AnyObject) {
self.mutableSetValueForKey("definitions").addObject(value)
}

func removeDefinitionsObject(value: AnyObject) {
// this method is never called
self.mutableSetValueForKey("definitions").removeObject(value)
}
}

var test = TestClass()
test.addDefinitionsObject("yo")

运行它会导致无限递归,最终会因 EXC_BAD_ACCESS 而崩溃。知道为什么会这样吗?

奇怪的是,只有在定义了 removeDefinitionsObject 时才会发生这种情况。如果我删除该功能,问题就会消失。

最佳答案

来自 "Accessor Search Pattern for Unordered Collections"在《Key-Value Coding Programming Guide》(强调我的):

The default search pattern for mutableSetValueForKey: is as follows:

  • Searches the receiver's class for methods whose names match the patterns add<Key>Object: and remove<Key>Object: (corresponding to the NSMutableSet primitive methods addObject: and removeObject: respectively) and also add<Key>: and remove<Key>: (corresponding to NSMutableSet methods unionSet: and minusSet:). If at least one addition method and at least one removal method are found each NSMutableSet message sent to the collection proxy object will result in some combination of add<Key>Object:, remove<Key>Object:, add<Key>:, and remove<Key>: messages being sent to the original receiver of mutableSetValueForKey:.
  • ...

这意味着如果addDefinitionsObjectremoveDefinitionsObject在你的类中实现,然后

self.mutableSetValueForKey("definitions").addObject(value)

通话

self.addDefinitionsObject(value)

因此递归。

关于swift - 为什么下面的代码会导致无限递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com