There is the code in one opensource project:
- (id) initWithContentPath: (NSString *) path parameters: (NSDictionary *) parameters
{
NSAssert(path.length > 0, @"empty path");
playPath = path;
self = [super initWithNibName:nil bundle:nil];
if (self) {
_moviePosition = 0;
_startTime = -1;
self.wantsFullScreenLayout = YES;
_decodeDuration = DEFAULT_DECODE_DURATION;
_minBufferedDuration = LOCAL_BUFFERED_DURATION;
_parameters = parameters;
__weak KxMovieViewController *weakSelf = self;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSError *error;
KxMovieDecoder *decoder;
decoder = [KxMovieDecoder movieDecoderWithContentPath:path error:&error];
NSLog(@"KxMovie load video %@", path);
__strong KxMovieViewController *strongSelf = weakSelf;
if (strongSelf) {
dispatch_sync(dispatch_get_main_queue(), ^{
[strongSelf setMovieDecoder:decoder withError:error];
});
}
});
}
return self;
}
I want to know when one class need to set self
to strong or weak?
A strong reference is used when you want to ensure the object you are referencing is not deallocated while you are still using it. A weak reference is used when you don't care if the object you are referencing is deallocated. A weak reference is automatically set to nil
when there are no more strong references to that object.
Basically, as long as there is at least one strong reference to an object, it won't be deallocated. When there are no more strong references, all weak references (if any) are set to nil
.