初始化后销毁回调块的对象

Object with callback block destroyed after init

我有这样的帮手class。

@interface CustomOnScreenshot : NSObject;

@property (copy) void (^finishedCallback)(id sender);

-(instancetype)initWithCallback: (void (^)(id sender))callback;

+(instancetype)onScreenshot:(void (^)(id sender))callback;

@end

@implementation CustomOnScreenshot

-(instancetype)initWithCallback: (void (^)(id sender))callback{
    self = [super init];
    if (self) {
        self.finishedCallback = callback;
        [self subscribeEvent];
    }
    return self;
}

+(instancetype)onScreenshot:(void (^)(id sender))callback{
    CustomOnScreenshot * onScreenShot = [self new];
    [onScreenShot setFinishedCallback:callback];
    return onScreenShot;
}

-(void)subscribeEvent{
    NSLog(@"CustomOnScreenshot subscribeEvent");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doOnScreenShot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}

-(void)unsubscribeEvent{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}

-(void)doOnScreenShot: (id)sender{
    if (self.finishedCallback) {
        self.finishedCallback(sender);
    }
}

-(void)dealloc{
    NSLog(@"CustomOnScreenshot dealloc");
    [self unsubscribeEvent];
}

问题是,如果你按预期使用它,那么对象会立即被销毁

- (void)viewDidLoad {
    [super viewDidLoad];
    [CustomOnScreenshot onScreenshot:^(id sender) {
        // CUSTOM code
    }];
}

日志:
CustomOnScreenshot subscribeEvent
CustomOnScreenshot 解除分配

只有当我在 属性 中使用结果时,一切都有效,但我发现这太过分了

@property (strong, nonatomic) CustomOnScreenshot * customOnScreenshot;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customOnScreenshot = [CustomOnScreenshot onScreenshot:^(id sender) {
        // CUSTOM code
    }];
}

如果您没有 CustomOnScreenshot 实例的强引用,那么对象将在 +onScreenshot: 后立即被 ARC 释放完成执行。

这就是 @property 修复它的原因。

如果您不想要 @property,那么我建议您使用单例。