2012-04-10 30 views
0

希望這是一個容易...的iOS:NSObject的呼叫,並檢測其中的UIViewController的呼籲

我有一個方法,一個NSObject是在多個UIViewControllers使用(NSObject的是我的.PCH文件導入) 。

UIViewControllers然後像這樣調用NSObject;

[ThisNSObject doSomething];

這是所有工作的計劃,所以沒有問題存在。不過,我會愛的方法DoSomething的能夠檢測哪個UIViewController中的呼籲,即NSObject的。然後,基於這些信息,我可以以任何給定的方式操作UIViewController。

我需要這個的原因是因爲如果我有一個UITabBar與每個選項卡加載不同的UIViewController,但都調用全局NSObject,我需要進一步的行動指向該特定的UIViewController。

我知道我有權訪問keyWindow,但我不確定這正是我所追求的。

任何建議會很好,謝謝。

羅伊

編輯: 其實,也許在NSObject的我能夠檢測出標籤當前選擇,然後得到在堆棧頂部查看...,並像一個參考?有沒有人有想過爲什麼這將是一個壞主意?

回答

0

使用運行時代碼,您可能會鑽回調用堆棧,但這對於一個簡單問題來說是相當複雜的解決方案。我建議你看看API的靈感和修改DoSomething的方法把控制器參數是這樣的:

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

時,你可以在DoSomething的方法,你傳遞引用自這樣的這樣:

[theObject doSomethingWithViewController:self]; 

而你的問題解決了 - 簡單。

P.S.如果您有其他參數,另一種簽名樣式可能是

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

這一切都取決於對您最好的意義。

+0

你說得對,我認爲這是最好的方法。 – roycable 2012-04-11 07:06:39

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"]; 

希望這有助於您。

+0

哎呀,教我輸入代碼而不是剪切和粘貼:-)將更正我的答案。 – drekka 2012-04-12 01:04:21