gpt4 book ai didi

iphone - 使用字符串中的对象运行方法

转载 作者:行者123 更新时间:2023-12-03 16:54:42 25 4
gpt4 key购买 nike

在我的代码的某一点,我将方法作为字符串引用,并且我有它们的目标。例如,假设我有一个名为 myObject 的对象,并且有一个名为“doSomething:”的方法,如下所示:

- (void)doSomething:(id)sender {
// do something baby
}

在我的代码的某一点,我存储了对执行此操作的对象和方法的引用:

NSString *myMethod = @"doSomething:";
id myTarget = myObject;

稍后,在代码的另一点我想这样做

[myObject doSomething:self];

但是如何从对象的引用 id 以及表示该方法的 NSString 重建对该对象的方法调用,以及如何将 self 传递给该方法?

谢谢

最佳答案

要将字符串转换为选择器,请使用NSSelectorFromString。相反,请使用 NSStringFromSelector。

转换选择器:

SEL selector = NSSelectorFromString(methodSelectorString);

调用方法:

[myObject performSelector:selector withObject:self afterDelay:0.0];
<小时/>

来自Foundation reference ;

NSSelectorFromString

返回具有给定名称的选择器。

SEL NSSelectorFromString (
NSString *aSelectorName
);

参数

aSelectorName

A string of any length, with any characters, that represents the name of a selector. Return Value The selector named by aSelectorName. If aSelectorName is nil, or cannot be converted to UTF-8 (this should be only due to insufficient memory), returns (SEL)0.

Discussion To make a selector, NSSelectorFromString passes a UTF-8 encoded character representation of aSelectorName to sel_registerName and returns the value returned by that function. Note, therefore, that if the selector does not exist it is registered and the newly-registered selector is returned.

Recall that a colon (“:”) is part of a method name; setHeight is not the same as setHeight:. For more about methods names, see “Objects, Classes, and Messaging” in The Objective-C Programming Language.

<小时/>
NSStringFromSelector

返回给定选择器的字符串表示形式。

NSString *NSStringFromSelector (
SEL aSelector
);

关于iphone - 使用字符串中的对象运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15067274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com