簡體   English   中英

__弱的通用變量聲明塊

[英]__weak general variables declaration for blocks

我目前正在研究使用許多塊的實現。 每個障礙都需要與自我溝通。

目前,我正在這樣做:

@implementation Foo
- (void) bar
{
    __weak Foo *weakSelf = self;
    [self doBlockStuff:^(id something) {
        [weakSelf doSomething];
    }];
}
@end

我有許多功能與弱實例化相同。

在接口塊中實例化弱屬性一次並在各處使用它是否正確?

它正在工作,但是被接受嗎?

@interface Foo ()
{
    __weak Foo *_weakSelf;  
}
@end

@implementation Foo
-(instancetype) init
{
    self = [super init];
    if(self) {
        _weakSelf = self;
    }
    return self;
}

- (void) bar1
{
    [self doBlockStuff:^(id something) {
        [_weakSelf doSomething];
    }];
}
- (void) bar2
{
    [self doBlockStuff:^(id something) {
        [_weakSelf doSomething];
    }];
}
- (void) bar3
{
    [self doBlockStuff:^(id something) {
        [_weakSelf doSomething];
    }];
}
- (void) bar4
{
    [self doBlockStuff:^(id something) {
        [_weakSelf doSomething];
    }];
}
@end

使用新信息進行測試后進行編輯:我確實編寫了一個小測試用例,現在我可以演示為什么第二個無法使用。 在我的Testclass中,在5秒后使用相關的自用信息發出了一個調度,當我調用dealloc時我記錄了日志。

@implementation Foo

- (void)dealloc
{
    NSLog(@"dealloc");
}

- (instancetype)init
{
    self = [super init];
    if (self) {

    }

    return;
}

- (void)bar
{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self doSomething];
    });
}

@end

如果該類丟失了所有者,因為控制器已關閉或其他原因並且該函數仍在運行,則在分派完成后,該類將進行對話。

@interface Foo ()
{
    __weak Foo *_weakSelf;  
}
@end

@implementation Foo

- (void)dealloc
{
    NSLog(@"dealloc");
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _weakSelf = self;
    }

    return;
}

- (void)bar
{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_weakSelf doSomething];
    });
}

@end

如果完成了分配,則這也會在dealloc上進行。 由於_weakSelf屬性仍在類中鑽研,因此是使用self-> _ weak的簡寫。 自我意味着自我:)

@implementation Foo

- (void)dealloc
{
    NSLog(@"dealloc");
}

- (instancetype)init
{
    self = [super init];
    if (self) {

    }

    return;
}

- (void)bar
{
     __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf doSomething];
    });
}

@end

由於弱引用僅存在於分配給該塊的該函數中,因此該函數將立即取消分配。 該函數已結束,如果該類丟失了其引用,則該塊將不具有阻礙任何人的屬性。 但是,當引用類可用時,弱屬性仍然可用。 可以肯定的是,該弱屬性將仍然存在,我們可以在該塊中設置一個強周期。

這根本不符合您的想法。 這些方法中的__weak實例變量? 那只是self->_weak的簡寫。 使用建議的方式的所有這些方法仍然可以很強地self捕捉。

堅持以前的做法。

如果__weakSelf仍然擁有很強的引用,那么這真的很糟糕。 問題是,如果在該方法中實例化並在該方法中使用它,它對自身的錨定是否仍然很弱,或者在那一刻它是否擁有強大的參照力。 根據文檔,您可以在塊外實例化一個弱引用,如果需要,甚至可以在塊內實例化一個弱引用。 在這里看看

http://aceontech.com/objc/ios/2014/01/10/weakify-a-more-elegant-solution-to-weakself.html

我此時的問題是,為什么當真實的self進行dealloc時,弱的self實例化將其self進行dealloc。 因為我試圖將弱的自身保留在另一個viewController中,然后取消分配實際的自我。 但是,一旦我解除了真實自我的分配,弱者就被解除了分配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM