Basic Objective-C syntax

2020-04-21 05:40发布

问题:

What is the difference between

cell.classHour.backgroundColor=[UIColor blackColor];

and

[cell.classHour setBackgroundColor:[UIColor blackColor]];

As you can see, I was trying to set the background color for a UILabel in a UITableViewCell. Somehow, the first method didn't work for me. I always thought both methods would do the same.

回答1:

tl;dr:

Both lines have 99.5% identical results.

What is the difference between [...]

The semantical difference is very subtle. In nearly all cases there is no difference in the compiled executable.

The first line, using property syntax, makes the compiler look for a matching property declaration. When it does not find one it will look for a matching setter declaration:

- (void)setBackgroundColor:(UIColor *)value;

The compiler will still accept dot notation when it finds a matching setter.

Even when there is a (default) property declaration ...

@property UIColor *backgroundColor;

... the compiler just inserts a call to setBackgroundColor:, as the property declaration implies that a setter of this name exists.

I always thought both methods would do the same.

As long as the static type of the receiver is known at compile time, dot notation and explicitly calling the setter are identical. If the static type of the receiver is id the compiler will not allow dot notation.

The only real difference between the two styles arises when there is a property declaration with an explicit setter name:

@property (setter=setColor) UIColor *backgroundColor;

In this (hypothetical) case the compiler will actually generate different code for the two lines: setColor: when using property syntax, setBackgroundColor: when using explicit message send.

Somehow, the first method didn't work for me.

The last part probably is not the reason for your problem. I added it to point out the single difference in message sending and property access.

While changing the getter name is common (for boolean properties) it's rare to use an explicit setter name. I have never seen this in Apple's frameworks.



回答2:

Both of these are pointing to same api. One chance may be an OS bug, please check the OS you are testing and test in other versions.