2010-03-05 7 views
5

다른 컨트롤러에서 하나의 뷰 컨트롤러에 정의 된 함수를 호출하고 싶습니다. I'v는 수백 가지 설정과 아무 것도 작동하지 않는 것처럼 보입니다.아이폰 용 다른 뷰 컨트롤러에서 함수 호출하기

기본 코드를 게시했으며 다른 사람들이 어떻게하는지 알려주고 싶습니다. 기본적으로 dealB 버튼을 누르면 GameViewController에서 SwitchViewController에 정의 된 MYBPress 함수를 호출하기 만하면됩니다. 어떤 도움이라도 대단히 감사하겠습니다. PS : 나는 오랜 시간 동안 코딩 만의 Obj-C

// ------- SwitchViewController.h --------------- 
#import <UIKit/UIKit.h> 
@class GameViewController; 
@class OptionsViewController; 

@interface SwitchViewController : UIViewController { 
OptionsViewController *optionsViewController; 
} 

@property (retain, nonatomic) OptionsViewController *optionsViewController; 
@property (retain, nonatomic) GameViewController *gameViewController; 
-(IBAction)MyBPress:(id)sender; 
@end 


// -------- GameViewController.h ------------ 

#import <UIKit/UIKit.h> 

@interface GameViewController : UIViewController { 
    IBOutlet UIButton *dealB; 
} 
@property(nonatomic,retain) IBOutlet UIButton *dealB; 
- (IBAction)dealB:(id)sender; 
@end 


// ------- GameViewController.m 
#import "GameViewController.h" 

@implementation GameViewController 
@synthesize dealB;   // The Deal button 

- (IBAction)dealB:(id)sender 
{ 
    // Here is where I want to call the MyBPress function 
} 

@end 

답변

5

에 realtivly 새로운 오전 한 "나는 다른 컨트롤러에서 하나의 뷰 컨트롤러에 정의 된 함수를 호출 할 위치 안녕 모두, 내가 문제가 있습니다. 나는 수백 가지의 다른 설정이있는 것처럼 보이고 아무 것도 작동하지 않는 것 같아. "

이것은 잘못된 디자인이기 때문입니다. 컨트롤러는 서로 직접 대화해서는 안됩니다.

당신은 대표, 통지 또는 일부 공유 중앙 엔티티를 사용하는 것이 좋습니다.

+0

감사합니다. 그것은 나쁜 디자인인가? 어쩌면 문제가 될 수 있습니다. –

+0

안녕하세요, St3fan, 돌아가서 NsNotificationCenter를 사용하여 다시 시도하고 작동하도록했습니다. 나는 그것을 일찍 시도했지만 분명히 올바르게하지는 않았다. 귀하의 코멘트를 다시보고 저를 얻었다 :-) 내 불만은 틀에 얽매이지 않는 방법을 시도하는 저를지도하고 나는 입력 주셔서 감사합니다, 그래서 그것을 알아 냈다. –

1

왜 그냥 버튼이 각각의 컨트롤러에 직접 모두 메시지를 보낼 수 있나요? UIButton의 인스턴스는 본질적으로 여러 메시지를 여러 대상에 보낼 수 있습니다. 버튼을 구성하려면 필요에 따라 다음과 같은 메시지를 여러 번 보낼 수 있습니다

- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents 

당신은 또한 같은 일을 할 수있는 인터페이스 빌더에서 버튼을 위로 연결할 수 있습니다. 또는 귀하의 마음에 맞는 내용을 믹스 앤 매치하십시오. 귀하의 의견

+0

그 정보를 보내 주셔서 감사합니다. 그것을 시도한 적이 없지만 나중에 참조 할 수 있도록 기억할 것입니다. –

25
/* Ok, so based on a suggestion to use Notifications, I solved my problem. It's 
actually so simple, it ridiculous I had so much trouble with it. Thought I'd 
post it just in case some other newbie hits the same type issue. 
*/ 

// in the SwitchViewController.m I added this. This sets it up so 
// when the dealNotification 
// is triggered, the HideBar function I have defined in SwitchViewController 
// gets called. 
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(HideBar) name:@"dealNotification" object: nil]; 


// in the GameViewController.m where I want to call the function in the other controller, 
// I added this and it send the notification to run the function 
[[NSNotificationCenter defaultCenter] postNotificationName:@"dealNotification" object: nil]; 
+0

이것은 나를 위해 완벽하게 작동했습니다. – sridvijay

+0

@Rick 아주 좋습니다 ... 감사합니다. – death7eater

관련 문제