zoukankan      html  css  js  c++  java
  • swift内存管理

    为了解决引用循环的问题。

     

    However, with ARC, values are deallocated as soon as their last strong reference is removed, making weak references unsuitable for such a purpose.

     

    Unowned References

    Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned keyword before a property or variable declaration.

    An unowned reference is expected to always have a value. As a result, ARC never sets an unowned reference’s value to nil, which means that unowned references are defined using nonoptional types.

    IMPORTANT

    Use an unowned reference only when you are sure that the reference always refers to an instance that has not been deallocated.

    If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.

     

    声明周期:属性为nil时,本体也会消失;组合关系;

    The Customer and CreditCard example shows a situation where one property that is allowed to be nil and another property that cannot be nil have the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.

     

    构造的哲学悖论:

    To cope with this requirement, you declare the capitalCity property of Country as an implicitly unwrapped optional property, indicated by the exclamation mark at the end of its type annotation (City!). This means that the capitalCity property has a default value of nil, like any other optional, but can be accessed without the need to unwrap its value as described in Implicitly Unwrapped Optionals.

     

    Because capitalCity has a default nil value, a new Country instance is considered fully initialized as soon as the Country instance sets its name property within its initializer. This means that the Country initializer can start to reference and pass around the implicit self property as soon as the name property is set.

     

    Don’t use an implicitly unwrapped optional when there’s a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

     

    同步异步的问题:

    If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference.

    同步的用unowned,异步的用weak。

     

  • 相关阅读:
    第二个冲刺
    实验四主存空间的分配和回收
    Sprint总结
    Sprint回顾
    Scrum项目5.0
    hibernate jpa 注解 @Temporal(TemporalType.DATE) 格式化时间日期,页面直接得到格式化类型的值
    获得HttpServletResponse及其他对象
    UUID.randomUUID()方法介绍
    psp个人软件过程需求文档
    电子产品自动搜索比价系统设计与实现 项目愿景与范围
  • 原文地址:https://www.cnblogs.com/feng9exe/p/8746619.html
Copyright © 2011-2022 走看看