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;@endHere, 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;}