2013-05-15 18 views
3

我仍在學習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方法棄用於其他內容?

+2

兩個是等價的(除來自編譯器檢查點符號的輕微語法差異)。如果#1工作,#2應該工作一致。 – 2013-05-15 21:49:56

+2

等待您將單元格從「cellForItemAtIndexPath:'轉換爲錯誤類型的UICollectionView。否則,這些值應該與@ H2CO3所表示的值相同 –

+0

在這兩種情況下編譯器都應該警告。我懷疑我們正在顯示的代碼是實際的代碼。 – matt

回答

1

當您使用點符號時,請始終記住,您不要需要以任何方式更改屬性名稱。所以,如果你說的有:

@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 
+0

感謝您糾正我,@ H2CO3。 –

相關問題