IOS about decorating the agent with weak or assign

Source: Internet
Author: User

1. For strong: The object strongly references delegate, the outside world cannot destroy the delegate object, which causes the circular reference (Retain Cycles)

Because our general agent is the current controller, such as Scrollview.delegate = self, this is a circular reference to the above circle. If delegate is a strong pointer, then the retaincount of Uiviewcontroller and ScrollView is always at least 1, so the object with the strong pointer is not destroyed, which results in a memory leak. So to avoid this kind of memory leak, that is, to avoid a circular reference like the above, it must be delegate as a weak pointer, so that when Uiviewcontrller runs out of its scope to be destroyed, it finds no strong pointer to itself, and retaincount= 0, so it is automatically destroyed, and it points to the UIView there is no strong pointer pointing, so retaincount=0, so also destroyed, so Nsarray also destroyed, the final ScrollView also destroyed, to avoid the problem of memory leaks.

2. For assing: also has the weak effect. But there is assign on the net is the pointer assignment, does not have the reference count operation, after the use if does not set to nil, may produce the wild pointer, but once the weak does not use, will never use, will not produce the wild pointer.

After some research, it is found that if you use

@property (nonatomic, assign, ReadWrite) ID delegate;

Declare a delegate, then even if delegate point to the object destroyed, delegate will still save the address of the previous object, that is, delegate became a wild pointer ...

3. For weak: Indicates that the object is not responsible for maintaining delegate object, delegate the destruction of this object is externally controlled.

While using weak, there is no such problem, when delegate points to the object destroyed, delegate = nil,

So the answer is, use weak.

IOS about decorating the agent with weak or assign

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.