从Objective-C块分配变量值 [英] Assigning a variable value from an Objective-C Block

查看:106
本文介绍了从Objective-C块分配变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Swift I can give a variable a value using an anonymous closure:

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

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

我试图在Obj-C中执行相同的操作,但这会在添加子视图并设置其框架时导致错误:

I am trying to do the same in Obj-C, but this results in an error when adding the subview and setting its frame:

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);

推荐答案

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

You're trying to write in Objective-C with Swift syntax. The Swift example describes a lazily initialized variable, while Objective-C one declares a simple block that returns UIImageView. You'd need to call the block with

[self addSubview:thumbnailImageView()];

但是,在这种情况下,使用块初始化变量没有什么意义.如果您正在寻找延迟初始化的属性,那么在Objective-C中看起来像这样

However, in this case using the block to initialize a variable makes little sense. If you're looking for lazily initialized properties, it would look like this in Objective-C

@interface YourClass : Superclass

@property (nonatomic, strong) UIImageView* imageView;

@end

@synthesize imageView = _imageView;

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

这篇关于从Objective-C块分配变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆