[OC] Create a new class in parentheses

Keywords: Mobile iOS Programming

[OC] Create a new class in parentheses

Special description

The following code is only for illustration purposes, naming is not a special specification, children do not imitate oh.

Preface

In iOS development, we often use such a piece of code:

UIView *myView = [UIView new];
myView.backgroundColor = [UIColor blackColor];
myView.layer.borderWidth = 2.f;
myView.layer.borderColor = [UIColor redColor].CGColor;
[self addSubview:myView];

It looks like it's okay to compile and run, but as we continue to write code, we'll write it:

UIView *myView1 = [UIView new];
myView1.backgroundColor = [UIColor blackColor];
myView1.layer.borderWidth = 12.f;
myView1.layer.borderColor = [UIColor whiteColor].CGColor;
[self addSubview:myView1];
UIView *myView2 = [UIView new];
myView2.backgroundColor = [UIColor blackColor];
myView2.layer.borderWidth = 7.f;
myView2.layer.borderColor = [UIColor redColor].CGColor;
[self addSubview:myView2];
UIView *myView3 = [UIView new];
myView3.backgroundColor = [UIColor yellowColor];
myView3.layer.borderWidth = 3.f;
myView3.layer.borderColor = [UIColor blueColor].CGColor;
[self addSubview:myView3];

So at this time we will see our code programming one by one, very ugly, this time we need a small way to improve the readability of the code. This method actually originated from the earliest time. GCC And was inherited into clang.

Statements and Declarations in Expressions

When we do assignment, we usually do this:

CGFloat t1 = 1.2;
CGFloat t2 = 3.1;
CGFloat a = t1 + t2;

In fact, we can still do this:

CGFloat a = ({
    CGFloat t1 = 1.2;
    CGFloat t2 = 3.1;
    CGFloat result = t1 + t2;
    result;
});

In fact, brackets are embedded in parentheses, where you can write multiple lines of code, and the last sentence is the result you want to return.
Finally, let's arrange the first block of code.

UIView *myView1 = ({
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor blackColor];
    view.layer.borderWidth = 12.f;
    view.layer.borderColor = [UIColor whiteColor].CGColor;
    view;
});
[self addSubview:myView1];
UIView *myView2 = [UIView new];
myView2.layer.borderWidth = 7.f;
myView2.layer.borderColor = ({
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor blackColor];
    view.layer.borderWidth = 7.f;
    view.layer.borderColor = [UIColor redColor].CGColor;
    view;
});
[self addSubview:myView2];
UIView *myView3 = ({
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor yellowColor];
    view.layer.borderWidth = 3.f;
    view.layer.borderColor = [UIColor blueColor].CGColor;
    view;
});
[self addSubview:myView3];

Well, that's it.

Seek reward

Posted by foochuck on Fri, 01 Feb 2019 11:18:15 -0800