开发者

Send a dynamic message at runtime to an object in Objective-c on iOS

开发者 https://www.devze.com 2023-04-04 15:09 出处:网络
Is it possible to craft a message at runtime and send it to an object in objective-c on iOS? Let\'s say I have an instance of class

Is it possible to craft a message at runtime and send it to an object in objective-c on iOS?

Let's say I have an instance of class Foo I want to be able to use something like

NSString * d = @"action1:";
[myFoo d]; 
d = @"action2:";
开发者_高级运维[myFoo d];

and Foo has at least two instant methods:

-(void) action1:(id)sender;
-(void) action2:(id)sender;


NSString *d = @"action1:";
SEL selector = NSSelectorFromString(d);
if ([myFoo respondsToSelector:selector])
{
    [myFoo performSelector:selector withObject:someObject];
}

There are a number of different performSelector methods on NSObject. You can call with no params, with delays, etc.

0

精彩评论

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