Weak References

http://docwiki.embarcadero.com/RADStudio/Seattle/en/Automatic_Reference_Counting_in_Delphi_Mobile_Compilers#Weak_References

Weak References

Another important concept for ARC is the role of weak references, which you can create by tagging them with [weak] attribute. Suppose that two objects refer to each other using a field, and an external variable refers to the first. The reference count of the first object will be 2 (the external variable, and the second object), while the reference count of the second object is 1. Now, as the external variable goes out of scope, the two objects‘ reference count remains 1, and they remain in memory indefinitely.

To solve this type of situation, and many similar scenarios, is to use a weak reference to break the circular references when the last external reference goes out of scope.

A weak reference is a reference to an object that does not increase its reference count. To declare a weak reference, use the [weak] attribute, supported by the Delphi mobile compilers.

Given the previous scenario, if the reference from the second object back to the first one is weak, as the external variable goes out of scope, both objects are destroyed. Here is an example of this situation:

type
  TMyComplexClass = class;
 
  TMySimpleClass = class
  private
    [Weak] FOwnedBy: TMyComplexClass;
  public
    constructor Create();
    destructor Destroy (); override;
    procedure DoSomething(bRaise: Boolean = False);
  end;
 
  TMyComplexClass = class
  private
    fSimple: TMySimpleClass;
  public
    constructor Create();
    destructor Destroy (); override;
    class procedure CreateOnly;
  end;

In the following code snippet, the constructor of the complex class creates an object of the other class:

constructor TMyComplexClass.Create;
begin
  inherited Create;
  FSimple := TMySimpleClass.Create;
  FSimple.FOwnedBy := self;
end;

Remember that the FOwnedBy field is a weak reference, so it does not increase the reference count of the object it refers to, in this case the current object (self).

Given this class structure, we can write:

class procedure TMyComplexClass.CreateOnly;
var
  MyComplex: TMyComplexClass;
begin
  MyComplex := TMyComplexClass.Create;
  MyComplex.fSimple.DoSomething;
end;

This causes no memory leak, given that the weak reference is properly used.

As a further example of the use of weak references, note this code snippet in the Delphi RTL, part of the TComponent class declaration:

type
  TComponent = class(TPersistent, IInterface,
    IInterfaceComponentReference)
  private
    [Weak] FOwner: TComponent;

If you use the weak attribute in code compiled by one of the desktop Delphi compilers, the attribute is ignored. Using DCC32, you have to make sure that you add the proper code in the destructor of an "owner" object to also free the "owned" object. Calling Free is allowed, although the effect is different in the Delphi mobile compilers. The behavior is correct in both in most circumstances.

Note: When an instance has its memory released, all active [weak] references are set to nil. Just as a strong (normal) reference, a [weak] variable can only be nil or reference a valid instance. This is the main reason why a weak reference should be assigned to a strong reference before being tested for nil and dereferenced. Assigning to a strong reference does not allow the instance to be released prematurely.

var
  O: TComponent;// a strong reference
begin
  O := FOwner;  // assigning a weak reference to a strong reference
  if O <> nil then
    O.<method>;// safe to dereference
end;

Note: You can only pass a [Weak] variable to a var or out parameter that is also marked as [Weak]. You cannot pass a regular strong reference to a [Weak] var or out parameter.

时间: 2024-12-16 22:25:35

Weak References的相关文章

The current deployment target does not support automated __weak references

下载运行一个demo时出现"The current deployment target does not support automated __weak references"这个问题,找了下方法: 4.2以前版本的XCode都不支持ARC. 对操作系统也有要求:Mac OS X v10.6 或 v10.7 (64-bit applications), iOS4或iOS5.注意:其中Mac OS X v10.6和iOS4不支持weak references(弱引用,后面会说明什么是w

Lua中的weak表——weak table(转)

弱表(weak table)是一个很有意思的东西,像C++/Java等语言是没有的.弱表的定义是:A weak table is a table whose elements are weak references,元素为弱引用的表就叫弱表.有弱引用那么也就有强引用,有引用那么也就有非引用.我们先要厘这些基本概念:变量.值.类型.对象. (1)变量与值:Lua是一个dynamically typed language,也就是说在Lua中,变量没有类型,它可以是任何东西,而值有类型,所以Lua中没

OC对象之旅 weak弱引用实现分析

Runtime源码分析带你了解OC实现过程.其中参考了大量的大神的代码以及文献里面也有个人的见解欢迎拍砖欢迎交流. 两种常见使用场景 /// weak属性@interface XX : [email protected](nonatomic,weak) Type* weakPtr;@end/// 代码块中使用{    /// 使用__weak     __weak Type* weakPtr = [[SomeObject alloc] init]; } 根据调试信息发现两者的区别是 第一种进入到

【高级java程序员应该知道的小知识】weak reference

本篇态度: simple & stupid weak reference Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. 弱引用不会阻止其引用的对象变成fin

Lua中的weak表——weak table

弱表(weak table)是一个很有意思的东西,像C++/Java等语言是没有的.弱表的定义是:A weak table is a table whose elements are weak references,元素为弱引用的表就叫弱表.有弱引用那么也就有强引用,有引用那么也就有非引用.我们先要厘这些基本概念:变量.值.类型.对象. (1)变量与值:Lua是一个dynamically typed language,也就是说在Lua中,变量没有类型,它可以是任何东西,而值有类型,所以Lua中没

Objective-C基础之_ weak, _ strong , __ block

上一篇文章中对于block做了一个全面的剖析和理解,那么在OBjective-C的block使用中我们难免会用到以上几个关键字,其实对于__block上篇文章已经做了解释,这篇文章,我会做几个关键字的区别和总结,来加深认识和理解. 上篇文章知道 clang -rewrite-objc 可以将OC代码转化成C代码C++代码,如果变量加上_ weak修饰,会发现无法转化,提示:cannot create _ weak reference because the current deployment

《流畅的Python》Object References, Mutability, and Recycling--第8章

Object References, Mutability, and Recycling 本章章节: Variables Are Not Boxes identity , Equality ,  Aliases Copies are shallow by default Function Parameters as references del and Garbage Collection Weak References Tricks Python Plays with Immutable Va

Java之道系列:WeakHashMap实现浅析

举个栗子 关于Reference对象,java.lang.ref包的文档说了一堆,跑起来看看才是王道, public class Foo { @Override protected void finalize() throws Throwable { System.out.println("finalize#" + this); super.finalize(); } } private static ReferenceQueue<Foo> queue = new Refe

为什么OC语言很难

作为一个Objective-C的coder,我总能听到一部分人在这门语言上抱怨有很多问题.他们总在想快速学习这门语言来写一个App出来,但他们也总是联想到Objective-C看上去实在太难了或者在想这些语法符号都是神马玩意?不错,他们问得非常好,所以本人也解释一下为什么很多程序员相比较学习Ruby或者Java很容易,但在决定开发iOS或者OS X应用时会那么犹豫. 语法: 首先我们谈谈神马叫做编程语言,编程语言是一种让人们能读懂并且能够展现程序的执行行为的语言,包括语法(正确的表达式以及状态机