在集合视图中设置背景颜色时,点语法与方括号

我仍然在学IOS SDK,所以希望这是有道理的。 我仍然试图围绕使用点语法的头。 有人可以解释为什么这个代码不起作用,但第二个呢?

不工作:

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath]; [[cell contentView] setBackgroundColor:[UIColor blueColor]]; } 

加工:

 -(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionView *cell = [collectionView cellForItemAtIndexPath:indexPath]; cell.contentView.backgroundColor = [UIColor blueColor]; } 

我只是不明白为什么第一个代码不会工作。 我正在使用最新版本的Xcode。 是否将setBackgroundColor方法弃用于其他内容?

当使用点符号时,请记住,您不需要以任何方式更改属性名称。 所以如果你说有:

 @property (nonatomic) NSString *message; 

编译器负责为你settergetter方法,所以你只需要在这个属性上使用点符号就可以了:

 self.message; // getter self.message = @"hi"; // setter // the only difference being - which side of the = sign is your property at 

另一方面,如果你想改变setter / getter的行为,那么你必须按照以下方式定义setMessage方法来实现(而不是覆盖)你自己的setter

 - (void)setMessage:(NSString *)message { // custom code... _message = message; } 

也许这就是你混淆的。 至于setBackgroundColor ,它仍然存在,你只是不使用点符号来访问它,顺便说一句,允许各种各样的整洁的东西,像这样:

 // .h @property (nonatomic) int someNumber; // .m self.someNumber = 5; // calls the setter, sets property to 5 self.someNumber += 10; // calls the setter and getter, sets property to 15 self.someNumber++; // calls the setter and getter, sets property to 16