objective-c - iOS 中的__weak 和__strong 属性有什么区别?

标签 objective-c ios6 weak-references strong-references

有一个开源项目的代码:

- (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;
}

我想知道一个类什么时候需要将self设置为strong或weak?

最佳答案

strong 引用用于确保您引用的对象在您仍在使用时不被释放。当您不关心所引用的对象是否被释放时,将使用 引用。当没有对该对象的强引用时,弱引用会自动设置为 nil

基本上,只要至少有一个对象的强引用,它就不会被释放。当没有更多的强引用时,所有弱引用(如果有的话)都设置为 nil

关于objective-c - iOS 中的__weak 和__strong 属性有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638703/

相关文章:

ios - RestKit 将未嵌套关系映射到拥有对象

ios - 大小与字体 : ConstrainedToSize: lineBreakMode: method is deprecated in iOS 7

uiscrollview - 如何在 AutoLayout (iOS6) 中使用 UIScrollView?

python - 如何删除 Python 中对象的每个引用?

.net - .Net中弱字典的良好实现

iphone - 由 .xib 或 .m 设计

ios - NSLineBreakByWordWrapping 在第一行,但 NSLineBreakByTruncatingTail 在第二行?

ios - 通过平滑的推送过渡和没有导航 Controller 来更改 View Controller

iPhone 耳机输出 - 单声道控制左/右耳

java - Android AsyncTask 中的弱引用与强引用