开发者

How to refer to instance properties at runtime in Objective-C

There is a trick Flash Actionscript developers can do to refer to instance properties at runtime. I was wondering if anything similar existed in Objective-C

In actionscript we can do:

var thisObject;
for (var i=0; i<10; i++) {
   thisObject = this["myInstanceProperty"+i];
   thisObject.doSomething();
}

I thought there would be a method similar to this in Objective-C, but I can't find anything mentioned anywhere. I'm looking for something along the lines of:

for (int i=0; i<10; i++) {
  NSString *buttonName = [NSString stringWithFormat:@"button_%i", i];
  id *thisButton = [self instancePropertyWithStringName:buttonName];
  thisButton.label = @"button %i";
}
开发者_如何学运维

Can you see what I'm getting at? I have a xib linking views to IBOutlets, and I'd like to refer to those IBOutlets from within a for loop, so I can add properties to them dynamically at runtime.

Any ideas?


You can use the following if the self object conforms to NSKeyValueCoding -- which it does by default for its instance variables and properties.

NSButton *button = [self valueForKey:buttonName];


It sounds like you're looking for a Key-Value Coding Guide.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜