【发布时间】:2013-02-01 02:17:47
【问题描述】:
在一个开源项目中有代码:
- (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设置为强或弱?
【问题讨论】:
-
我认为代码实际上并不正确。由于没有保留块,因此无需使用
weakSelf。 -
@CarlVeazey 项目在github.com/kolyvan/kxmovie,运行良好,但复制(合并)代码到其他项目时无法运行
-
理解强与弱是 Objective-C 中一个非常重要的概念,并且通常在任何课程/书籍的早期都涉及到。如果您的问题是针对代码的(“我理解强弱,但我不明白它是如何在此代码中使用的”),请重新措辞以明确这一点。如果您正在寻找一般的理解,我建议您阅读 Objective-C 参考,因为它对您未来的所有代码都很重要。此外,该问题已在此处讨论:stackoverflow.com/questions/9262535/…
标签: objective-c ios6 weak-references strong-references