当你这样写一段代码时:
self.imageView = [[UIImageView alloc] init];
self.imageView.backgroundColor = [UIColor redColor];
self.imageView.image = [UIImage imageNamed:@"12345"];
self.imageView.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:self.imageView];
其实可以使用语法糖来表达:
self.imageView = ({
UIImageView *imageView = [[UIImageView alloc] init];
imageView.backgroundColor = [UIColor redColor];
imageView.image = [UIImage imageNamed:@"12345"];
imageView.frame = CGRectMake(0, 0, 100, 100);
[self.view addSubview:imageView];
imageView;
});他们表达的意思是完全一样的。由于这些代码太基础了,看不出多少逼格的提升。
所以你也完全可以参考这两段代码,把一些复杂的代码写到语法糖里
本文介绍了一种在Objective-C中使用语法糖简化代码的方法,通过一个具体的UIImageView实例化过程展示了如何将一系列设置属性的操作封装成简洁的形式。
2070





