Dot syntax vs square brackets when setting background color in collection view

微笑、不失礼 提交于 2019-12-23 20:07:12

问题


I'm still learning IOS SDK so hopefully this makes sense. I am still trying to wrap my head around using dot syntax. Could some one explain why this code doesn't work but the second one does?

Not working:

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

Working:

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

I just don't understand why the first code won't work as well. I am using the newest version of Xcode. Was the setBackgroundColor method deprecated into something else?


回答1:


When you use dot notation, always keep in mind that you don't need to change the property name in any way. So if you say have:

@property (nonatomic) NSString *message;

The compiler takes care of the setter and getter methods for you, so all you have to do to use the dot notation on this property is this:

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

If on the other hand you want to change the behaviour of the setter/getter, you then have to you define the setMessage method in the following way, to implement (not override) your own setter:

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

Maybe that's what you're confusing. As for setBackgroundColor, it's still there, you just don't access it using the dot notation, which, by the way, allows for all kinds of neat stuff like this:

// .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


来源:https://stackoverflow.com/questions/16575545/dot-syntax-vs-square-brackets-when-setting-background-color-in-collection-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!