关于restkit:当使用@weakify,@ strongify时,我是否必须使用__block?

When using @weakify, @strongify, do I have to use __block?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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


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

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