1

我想获取我所在的当前函数的参数名称,以便如果当前实例上不存在该对象,我可以准备从文件系统加载该对象。(例如,如果 [foo dictTest] 不可用,我想将它之前保存的 plist 版本加载到该 ivar 中)

我想通过提供我作为参数提供给当前函数的 ivar 名称来查找文件。

这是功能代码:

-(NSDictionary*)getCachedDictionary:(NSDictionary*)dict{

    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:_cmd]];
    NSString * firstArgument = nil;
    [invocation getArgument:&firstArgument atIndex:2];
    NSLog(@"Trying to get the objects ivar %@",firstArgument);

    // right now during testing return nil
    return nil;
   }

一旦代码到达 NSLog,我就会从 firstArgument 获得一个空值。

这是为什么?有没有可能我必须等待我所在的当前方法的完整调用,或者创建一个代理函数实际上更好,该函数通过调用 setArgument 提供的 ivar 名称来隐式调用我的类方法,这样我可以像我想要的那样使用那个参数字符串吗?

提前非常感谢!

PS:在这个特定的示例中,我不想使用 KVC 来识别 ivar 并返回它。

4

2 回答 2

2

您误解了NSInvocationAPI。 +[NSInvocation invocationWithMethodSignature:]创建一个新NSInvocation的键控来接受方法签名定义的类型的参数。它不返回对应NSInvocation于当前方法调用的一个。这很容易看出原因:

- (void)doBar:(id)bip {
  NSLog(@"hi there!")
}

- (void)doFoo {
  NSMethodSignature *sig = [self methodSignatureForSelector:@selector(doBar:)];
  NSInvocation *i = [NSInvocation invocationWithMethodSignature:sig];
}

doFoodoBar:方法创建调用时,很明显可以看到参数必须为空,因为doBar:尚未执行,因此没有参数。更改@selector(doBar:)_cmd不会神奇地改变任何东西。

那么下一个问题:没有办法NSInvocation为当前方法调用获取一个?从来没听说过。 NSInvocation是一个极其复杂的类,从当前方法构造一个将是一场噩梦。

我强烈建议找到一种不同的方法来做你想做的任何事情。

于 2012-01-29T16:56:24.637 回答
1

尽管这个问题已经过时并且得到了解答,但这里有一个链接,它提供了一种简单且非常优雅的方式来为编译时已知的任何选择器/方法创建调用实例:

http://www.cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html

于 2015-04-21T19:25:24.213 回答