【问题标题】:When using @weakify, @strongify, do I have to use __block?当使用@weakify、@strongify 时,我必须使用__block 吗?
【发布时间】:2014-12-10 16:31:31
【问题描述】:

假设我的类有一个名为hotspotsOperation 的实例变量(我使用的是RestKit)并在块内使用(RestKit 的NSOperation)。我这样做是因为我希望能够取消正在进行的请求。但是我有一个关于保留周期的问题,__block。 基本上,在使用弱化/强化时我必须使用 __weak 吗? 还有一个问题,如果我不使用weakify/strongify而是将hotspotsOperation从strong改为weak,分析器说没有retain cycle,对吗?使用弱而不是弱化/强化更好?在这种情况下,self 会发生什么,被保留? 非常感谢您的任何建议。

#import "HotspotsService.h"
#import "Constants.h"
#import "Restkit.h"
#import "Hotspot.h"
#import <EXTScope.h>

@interface HotspotsService()
@property (nonatomic,strong) RKObjectManager *objectManager;
@property (nonatomic,strong) RKObjectRequestOperation *hotspotsOperation;
@end

@implementation HotspotsService

-(id) init {
    self=[super init];
    if (self) {
        // restkit
        // mapping
        // response
    }
    return self;
}

-(void) hotspotsWithRadius:(NSUInteger)rad center:(CLLocationCoordinate2D)coordinate onSuccess:(void(^)(NSArray *hotspots))success onFailure:(void(^)(NSError *error))fail {
    [self cancelHotspotsRequest];
    NSDictionary *params = // params
    self.hotspotsOperation = [self.objectManager appropriateObjectRequestOperationWithObject:nil method:RKRequestMethodGET path:kSolrPath parameters:params];
    @weakify(self);
    [self.hotspotsOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        @strongify(self);
        self.hotspotsOperation=nil;
        success(mappingResult.array);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        @strongify(self);
        self.hotspotsOperation=nil;
        fail(error);
    }];
    [self.objectManager enqueueObjectRequestOperation:self.hotspotsOperation];
}

-(void) cancelHotspotsRequest {
    [self.hotspotsOperation cancel];
    self.hotspotsOperation=nil;
}

@end

【问题讨论】:

  • 你为什么不直接使用cancelAllObjectRequestOperationsWithMethod:matchingPathPattern:
  • 感谢您的回复。在这种情况下可以工作,但问题是可能同时有其他请求我不想取消。无论如何,我的问题是关于块保留周期管理。有什么建议吗?谢谢。

标签: restkit objective-c-blocks


【解决方案1】:

我会让hotspotsOperation 属性变弱,因为您将操作传递给 RestKit 来管理,而您只关心它的生命周期 - 您没有兴趣在此生命周期后拥有它。这也意味着您不需要在块中捕获self

如果您在由self 拥有的对象保留的块中捕获self,那么您应该使用弱引用。如何做到这一点取决于您,但@weakify 似乎非常方便和简单。

【讨论】:

  • 如果我使用weak,我必须使用@weakify/strongify吗?
  • @weakify 可以方便地减少您编写的代码并帮助您记住强项...
猜你喜欢
  • 1970-01-01
  • 2021-08-02
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
相关资源
最近更新 更多