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

时间:2015-03-19 12:19:38

标签: ios objective-c swift

我想将以下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(...)

1 个答案:

答案 0 :(得分:0)

您可以将结果翻译为

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