从Objective-C块分配变量值

时间:2017-08-29 14:23:55

标签: objective-c objective-c-blocks

在Swift中,我可以使用匿名闭包为变量赋值:

let thumbnailImageView: UIImageView = {
   let imageView = UIImageView()
   imageView.backGroundColor = UIColor.blueColor()
   return imageView;
}

addSubView(thumbnailImageView)
thumbnailImageView.frame = CGRectMake(0,0,100,100)

我试图在Obj-C中做同样的事情,但这会在添加子视图并设置其框架时导致错误:

UIImageView* (^thumbnailImageView)(void) = ^(void){
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.backgroundColor = [UIColor blueColor];
    return imageView;
};

[self addSubview:thumbnailImageView];

thumbnailImageView.frame = CGRectMake(0, 0, 100, 100);

1 个答案:

答案 0 :(得分:0)

您正尝试使用Swift语法编写Objective-C。 Swift示例描述了一个延迟初始化的变量,而Objective-C声明了一个返回UIImageView的简单块。您需要使用

调用该块
[self addSubview:thumbnailImageView()];

但是,在这种情况下,使用块来初始化变量毫无意义。如果您正在寻找延迟初始化的属性,它将在Objective-C

中看起来像这样
@interface YourClass : Superclass

@property (nonatomic, strong) UIImageView* imageView;

@end

@synthesize imageView = _imageView;

- (UIImageView*)imageView
{
    if (!_imageView) {
        // init _imageView here
    }
    return _imageView;
}