What's the difference between __weak and __strong included in iOS?

Hi there is some code in one open source 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 should set self

to strong or weak?

+3


source to share


2 answers


A strong link is used when you want the object you are referencing to not be freed while you are still using it. Weak reference is used when you don't care if the object you are referencing is freed. A weak reference is automatically set to nil

when there are no stronger references to that object.



Basically, as long as there is at least one strong reference to an object, it will not be deallocated. When there are no stronger links, all weak links (if any) are set to nil

.

+4


source


If you are looking for a clear explanation of the code you posted, I can try to help with that. I posted a similar hypothesis question about what is going on and am awaiting a response to test or invalidate my hypothesis.

My question is here: Explain reasons for __weak and __strong usage in SDWebImage code

To summarize, here's what I think: This code initializes an instance of the class. But it needs to run an asynchronous block. The __weak and __strong keywords are used to verify that the instance remains valid when the asynchronous block starts. If the instance has been freed then there is no need to perform the "setMovieDecoder" action.



To answer your specific question, you want to use this code pattern whenever you run an asynchronous block that needs to update an object instance, and you need that instance to update it. Don't use this code pattern for async blocks that simply load something like sync engines.

**** Disclaimer: Check out the answers to my clarified question in hopes of getting a real expert explanation of the code above. I hope I'm right.

+1


source







All Articles