iOS:NSObject调用并检测哪个UIVIewController进行了调用

时间:2012-04-10 01:05:23

标签: ios uiviewcontroller nsobject

希望这是一个简单的...

我有一个NSObject,其中包含在多个UIViewControllers中使用的方法(NSObject是在我的.pch文件中导入的。)

然后UIViewControllers像这样调用NSObject;

[ThisNSObject doSomething];

这一切都在计划,所以那里没有问题...但是,我希望方法 doSomething 能够检测到WHICH UIViewController对该NSObject的调用。然后,基于该信息,我可以以任何给定的方式操作UIViewController。

我需要这个的原因是因为如果我有一个UITabBar,每个Tab加载一个不同的UIViewController,但都调用全局NSObject,我需要将一个特定的UIViewController指向进一步的动作。

我知道我可以访问 keyWindow ,但我不确定这正是我所追求的。

任何建议都会很棒,谢谢。

罗伊

修改 实际上,也许在NSObject中我可以检测到当前选择了哪个选项卡,然后获取堆栈中的顶级视图...并进行类似的引用?有没有人想过为什么这会是一个坏主意?

2 个答案:

答案 0 :(得分:1)

我同意@ drekka的回答,但它有一个问题...代码行:

- (void) viewController:(UIVIewController*)viewController doSomething;

在语法上不正确。但是,他通过提出另一个正确的解决方案来赎回自己:

- (void) doSomethingWithViewController:(UIViewController*) viewController;

另一种选择,因为看起来传递ViewController作为参数在你的情况下确实有意义,就是在你的自定义类上使用委托并让viewController订阅为委托。例如:

@protocol MyCustomNSObjectDelegate;

@interface MyCustomNSObject : NSObject

@property (nonatomic, assign) id<MyCustomNSObjectDelegate delegate;

- (void) doSomething;

@end

@protocol MyCustomNSObjectDelegate <NSObject>
@required
- (void) myCustomNSObject:(MyCustomNSObject*)myObject takeFurtherActionWithData:(NSString*)someData;
@end

然后在你的UIViewController

#import "MyCustomNSObject.h"

@interface MyUIViewController : UIViewController <MyCustomNSObjectDelegate>

...

然后在调用doSomething之前将MyCustomNSObject的委托属性设置为UIViewController。在doSomething方法中,如果完成“某事”后,在方法结束时添加:

[self.delegate myCustomNSObject:self takeFurtherActionWithData:@"change this to whatever type you need here"];

希望这有帮助。

答案 1 :(得分:0)

使用运行时代码,您可能可以在调用堆栈中向后钻取,但对于一个简单的问题,它是一个相当复杂的解决方案。我建议您查看API以获取灵感,并修改您的doSomething方法以获取这样的控制器参数:

-(void) doSomethingWithViewController:(UIViewController *) viewController;

这样,当你可以使用doSomething方法时,你可以像这样传递对self的引用:

[theObject doSomethingWithViewController:self];

你的问题就解决了 - 简单。

P.S。如果您有其他参数,则可以使用其他签名样式

-(void) viewController:(UIViewController *) viewController doSomethingWithX:(id) x;

这一切都取决于对你最有意义的东西。