2015-11-20 24 views
2

我對這種語言很陌生,但對其他人有很好的把握。動態字段物業名稱目標C

我想知道如何動態訪問目標c中的字段名稱屬性。

喜歡的東西:

self.bottomText.text = @"foo"; 

要:

NSString *bottomText = @"bottomText"; 

self[bottomText].text = @"foo"; 

我能理解怎麼會是可以設置這樣的屬性(如每重複關口):

[self setValue:value forKey:@"propertyName"]; 

但在我看來,要麼必須沿着以下方向行事:

[self.bottomText setValue:@"foo" forKey:@"text"]; 

這並不能真正解決問題,或者是這樣的:

[self setValue:bottomText forKey:property].text = @"foo"; 

不知道是什麼性質。

或許:

[self valueForKey:bottomText].text = @"Test"; 

但沒有愛。

超級困惑這一個。

+1

@Drew我不同意。應該使用評論來發布已經嘗試過的東西,沒有奏效的想法或者與這個問題直接相關的任何信息應該*不鼓勵*。如果我在評論中看到類似內容,我可能會發表評論,表示應該將其添加到問題中。無論如何,我投票重新開放。它與鏈接的帖子有關,但不是重複的。 –

+0

夠公平的。只需將它標記爲*編輯:*即可進行後關閉嘗試 – Drew

回答

1

我很不確定,我是否理解你的Q正確。但笑着KVC應該解決您的問題:

NSString *bottomText = @"bottomText"; 
[self valueForKey:bottomText].text = @"foo"; 

NSString *property = @"bottomText.text"; 
[self setValue:@"foo" forKeyPath:property]; 

此外,該級的self可以實現keyed subscription

1

好吧,假設bottomTextUILabel(因爲它有一個text財產......),你可以做這樣的事情:

SEL selector = NSSelectorFromString(@"bottomText"); 
UILabel *label = (UILabel *)[self performSelector:selector]; 
label.text = @"Test"; 

,或者如果你真的想在同一行:

[(UILabel *)[self performSelector:NSSelectorFromString(@"bottomText")] setText:@"Test"];