简体   繁体   English

iOS Swift到Objective-C如何将弱引用传递给数组?

[英]iOS Swift to Objective-C how to pass weak references to arrays?

I would like to understand how Swift and objective-c handle passing around nil references. 我想了解Swift和Objective-C如何处理nil引用的传递。 I know that I cannot add nil to an Objective-C mutable array. 我知道我不能将nil添加到Objective-C可变数组。

How nil is handled in the following scenario: 在以下情况下如何处理nil:

  • Swift class is a weak reference observer passed to Objective-C class Swift类是传递给Objective-C类的弱引用观察者
  • Objective-C saves the reference to Swift class in an array Objective-C将对Swift类的引用保存在数组中
  • Swift class is dealocated, it's weak reference turns to nil Swift类已取消分配,它的弱引用变为nil
  • Objective-C's now has an array with one of the elements pointing to nil Objective-C现在有一个数组,其中一个元素指向nil

Does Objective-C class keep functioning, or does it crash when trying to iterate over the array and getting a nil reference? Objective-C类是否继续运行,还是在尝试遍历数组并获取nil引用时崩溃?

Unless you are using NSPointerArray , when you add the object to an array the array will hold a strong reference to it, preventing the object from being released. 除非您使用NSPointerArray ,否则在将对象添加到数组时,该数组将保留对其的强烈引用,从而防止对象被释放。

Only after the object is removed from the array, or the array itself is released will the object be eligible for deallocation. 仅在从数组中删除对象或释放数组本身之后,该对象才有资格进行释放。

This means that the array cannot be left holding a nil reference. 这意味着数组不能保留nil引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM