Understand
- Variable
- Scope
- Variable abandonment
- Holding objects
- Releasing objects
- Object owner (reference count)
- Object abandonment
- The effect of variable ownership modifiers on objects
Objects holding each other cause a cyclic strong reference, such as a target object for a Nstimer object that repeatedly executes a task
The timer object is preserved, and if the Nstimer object is held by the target object, a cyclic strong reference must occur because the Nstimer object will hold the target.
The Nstimer object is also the target object's member variable, which is the target object and holds the Nstimer object.
This cyclic strong reference persists until the target object calls the Invalidate method of the Nstimer object to release the Nstimer object
You can use the block and __weak ownership modifiers to resolve the cyclic strong reference by extending the Nstimer class
#import <Foundation / Foundation.h>
@interface NSTimer (BlocksSupport)
+ (NSTimer *) scheduledTimerWithTimeInterval:
(NSTimeInterval) interval
block: (void (^) ()) block
repeats: (BOOL) repeats;
@end
@implementation NSTimer (BlockSupport)
+ (NSTimer *) scheduledTimerWithTimeInterval:
(NSTimeInterval) interval
block: (void (^) ()) block
repeats: (BOOL) repeats
{
return [self scheduledTimerWithTimeInterval: interval
target: self
selector: @selector (blockInvoke :)
userInfo: [block copy]
repeats: repeats];
}
+ (void) blockInvoke: (NSTimer *) timer {
void (^ block) () = timer.userInfo;
if (block) {
block ();
}
}
// When using other Class
-(void) startAction {
__weak Class * weakSelf = self; // Define a weak reference to yourself
_myTimer = [NSTimer scheduledTimerWithInterval: 5.0 block: ^ {
Class * strongSelf = weakSelf; / * The block captures the weak reference pointing to itself, and does not directly capture the ordinary self variable, so the block does not hold the Class object
Then immediately let the __strong variable hold the __weak Class object to ensure that the instance continues to survive during execution,
In other words, strongSelf also holds the Class object, but, however, strongSelf is in the block body
The variables declared in, only have block blocks in their life cycle, and are released after the block block is executed, so they do not hold Class objects * /
[strongSelf excueAction];
} repeats: YES];
}
-dealloc {
[_myTimer invalidate]; / * When the outside world holds the last reference of the Class object to release it, this method will be executed, which will also stop the timer.
If the developer forgets to call the invalidate method in dealloc to stop the timer, the weakSelf in the block executed by the timer will become nil
strongSelf also points to nil, so the timer performs a no-op. * /
}
Analysis of OBJECTIVE-C memory management and examples of cyclic strong references