2009-06-18 6 views
2

안녕 얘들 아! 나는이 작은 문제가 있습니다하위 뷰에서 메서드 호출

을 내가 가지고 나는 이런 식으로 뭔가 그래서 내의 ViewController에서이 개 하위 뷰를 추가 하나의 ViewController :

//in my viewController.m i have this: 
- (void)startIcons 
{ 
    IconHolder *newIconHolder = [[IconHolder alloc] initWithItem:@"SomeItenName"]; 
    [self.view addSubview:newIconHolder]; 
} 
- (void)onPressIcon targetIcon(IconHolder *)pressedIcon 
{ 
    NSLog(@"IconPressed %@", [pressedIcon getName]); 
} 

을 그리고 이것은 내 서브 클래스 touchs입니다 : 이제

//And in my IconHolder.m i have this: 
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
} 

: 어떻게하면됩니까? 가장 좋은 방법은 내 ViewController를 저장하기 위해 생성자에서 연결을 만드는 것입니다. 내가 어떻게해야하니?

감사합니다.

답변

1

예, 의심스러운 링크를 만들어야합니다.

보기에 멤버 변수 MyViewController* viewController을 추가하고보기를 만들 때 설정하십시오. 똑똑 해지기를 원하면 속성으로 만들 수 있습니다.

보기에서 viewController를 유지해서는 안됩니다.보기가 이미 컨트롤러에 의해 유지되고 다른 방법으로 유지할 경우 유지주기가 생성되어 누수가 발생합니다.

0

연결을 만드는 대신 알림을 사용하는 방법이 있습니다. 예를 들어

, IconHolder.h에

extern const NSString* kIconHolderTouchedNotification; 

IconHolder.m에서

CONST는 NSString * kIconHolderTouchedNotification = @ "IconHolderTouchedNotification"; 컨트롤러에서 다음

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    //Here i need to call the method onPressIcon from my ViewController 
    [[NSNotificationCenter defaultCenter] kIconHolderTouchedNotification object:self]; 
} 

- (void) doApplicationRepeatingTimeChanged:(NSNotification *)notification 
{ 
    IconHolder* source = [notification object]; 
} 

- (IBAction) awakeFromNib; 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doIconHolderTouched:) name:kIconHolderTouchedNotification object:pressedIcon]; 
} 

- (void) dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name: kIconHolderTouchedNotification object:pressedIcon]; 
    [super dealloc]; 
} 

알림 당신은 객체 사이의 매우 약한 결합을 원하고 양방향 통신 (즉, IconHolder이 내용은 컨트롤러를 요청할 필요가 없습니다 필요하지 않은 경우 특히 좋다) 또는 둘 이상의 오브젝트를 알릴 필요가있는 경우.

관련 문제