【问题标题】:How to make weak reference to self in class function in Swift?如何在 Swift 的类函数中对 self 进行弱引用?
【发布时间】:2015-03-19 12:19:37
【问题描述】:

我想将以下 Objective-c 代码翻译成 Swift:

+ (void)someClassFunction {
   __weak __typeof(self)weakSelf = self;
}

我的结果是:

class func someClassFunction() {
   var weakSelf = self
}

问题是我不能在方法中应用weak

如何在 Swift 的类函数中对 self 进行弱引用?

这是我要翻译的代码:

__weak __typeof(self)weakSelf = self;
    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection
    completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer != NULL) {
            NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
            UIImage *image = [UIImage imageWithData:imageData];
            UIImage *croppedImage = [weakSelf cropImage:image withCropSize:cropSize];
            completion(croppedImage);
        }
    }];


+ (UIImage *)cropImage:(UIImage *)image withCropSize:(CGSize)cropSize
{
...
}

编辑:

我真的需要 Swift 中的星期参考,还是我可以只执行以下操作?

ClassName.cropImage(...)

【问题讨论】:

  • 为什么需要这样做?通常还有其他方法可以打破保留周期。
  • @JakubVano 我发布了更多代码。希望对您有所帮助。
  • 通常?这取决于您是否要将块存储在self 的属性中(或由self 保留的对象或由self 保留的对象保留的对象......)您一般不能这么说。
  • @AminNegm-Awad 我并不是在暗示每种情况都有相同的解决方案。我只是说,除了直接翻译提供的 objc 代码之外,还有其他方法可以打破保留周期。

标签: ios objective-c swift


【解决方案1】:

你可以把闭包翻译成

{[weak self] imageDataSampleBuffer, error in
    // self is weak in this closure
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2014-07-26
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多