IOS is easy to introduce three scenarios of "loop reference"

Source: Internet
Author: User

IOS is easy to introduce three scenarios of "loop reference"

In my reading, I have summarized four scenarios that are prone to circular references on the iOS platform:

1. parent-child mutual possession and delegation Mode

[Case ]:

@interface FTAppCenterMainViewController (){}@property(weak,nonatomic) UITableView* myTableView;@end
Here, the myTableView uses the weak modifier.

@property (nonatomic, weak)  id
 
  delegate;
 

[Recommended method ]:

Child only has parent objects of weak type:

@property (nonatomic, weak)  id
 
  delegate;
 

Ii. block

[Case ]:

See the following code:

typedef void (^RequestNaviCallBack)(NSInteger naviCode,NSInteger httpCode,NSError * error);@interface FtNaviManager : NSObject{}@property (nonatomic, strong)   RequestNaviCallBack naviCallBack;
This is a request navigation class. The class property holds RequestNaviCallBack. At this time, if RequestNaviCallBack Holds self again, it will inevitably cause loop reference.

[Recommended method ]:

If circular references exist, the compiler prompts a warning.

If the object does not hold a Block object, circular reference is not generated. If the object holds a block object, it is defined as follows when the block references self:

__weak typeof(self) weakSelf = self;

Iii. NSTimer

[Case ]:

@ Interface FtKeepAlive: NSObject {NSTimer * _ keepAliveTimer; // send heartbeat timer} // implementation file _ keepAliveTimer = [NSTimer timer: _ expired target: self selector: @ selector (keepLiveStart) userInfo: nil repeats: YES];

The class holds _ keepAliveTimer and _ keepAliveTimer Holds self, resulting in loop reference.

[Recommended method ]:

Nstdate will hold the object. Therefore, before deleting the object, you must use the invalidate method of timer.

-(void)stopKeepAlive{    [_keepAliveTimer invalidate];    _keepAliveTimer = nil;}

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.