2013-05-09 7 views
-1

에 도움이 필요합니다.AppDelegate에서 ViewController로 알림 전송

-(BOOL)application:(UIApplication *)application 
      openURL:(NSURL *)url 
sourceApplication:(NSString *)sourceApplication 
     annotation:(id)annotation { 
    if (url != nil && [url isFileURL]) { 
     //Valid URL, send a message to the view controller with the url 
    } 
    else { 
     //No valid url 
    } 
    return YES; 

을하지만 지금, 나는 AppDelegate에에하지만 내의 ViewController에 URL을 필요가 없습니다 : 나는 AppDelegate.m 이러한 위임 방법을 구현한다. URL을 "보낼"수있는 방법 또는 ViewController 이러한 위임 메서드를 구현할 수있는 방법?

답변

12

에 대한 자세한 내용은

[[NSNotificationCenter defaultCenter] 
    addObserver:self 
    selector:@selector(getData:) 
    notificationName:@"Data" 
    object:nil]; 

- getData:(NSNotification *)notification { 
    NSString *tappedIndex = [[_notification userInfo] objectForKey:@"KEY"]; 
} 

아래와 같이 같은 앱 위임에

첫째

후 알림 :

NSDictionary *_dictionary=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%d",newIndex],nil] forKeys:[NSArray arrayWithObjects:SELECTED_INDEX,nil]]; 

[[NSNotificationCenter defaultCenter] postNotificationName:SELECT_INDEX_NOTIFICATION object:nil userInfo:_dictionary]; 

다음 원하는의 ViewController를 등록 이 알림을 다음과 같이 확인하십시오 :

/***** To register and unregister for notification on recieving messages *****/ 
- (void)registerForNotifications 
{ 
    [[NSNotificationCenter defaultCenter] addObserver:self 
              selector:@selector(yourCustomMethod:) 
               name:SELECT_INDEX_NOTIFICATION object:nil]; 
} 

/*** Your custom method called on notification ***/ 
-(void)yourCustomMethod:(NSNotification*)_notification 
{ 
    [[self navigationController] popToRootViewControllerAnimated:YES]; 
    NSString *selectedIndex=[[_notification userInfo] objectForKey:SELECTED_INDEX]; 
    NSLog(@"selectedIndex : %@",selectedIndex); 

} 

호출이 등의 viewDidLoad 메서드 :

- (void)viewDidLoad 
{ 

    [self registerForNotifications]; 
} 

다음 언로드에이 메서드를 호출하여이 관찰자를 제거 :

-(void)unregisterForNotifications 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SELECT_INDEX_NOTIFICATION object:nil]; 
} 


-(void)viewDidUnload 
{ 
    [self unregisterForNotifications]; 
} 

은 당신을 도움이되기를 바랍니다.

5

알림 수신자가 구독하기 위해 알림 이름을 사용하는 지역 알림을 게시 할 수 있습니다.

[[NSNotificationCenter defaultCenter] 
    postNotificationName:@"Data" 
    object:nil]; 

그리고 viewController에서 알림을 구독하십시오. 당신이 NSNotificationCenter를 사용할 수있는 NSNotificationCenter Can go with this link

+0

내가이 코드를 삽입해야 안녕하세요 : [[NSNotificationCenter defaultCenter] addObserver : 자기 선택 : @selector (GetData의 : notificationName : "데이터"@ 개체 : yourdata] – Marv

+0

viewDidLoad로 호출 할 수있는 것처럼 알림 데이터를 확인하려는 경우 – Buntylm

+0

viewData에서 yourData를 어떻게 객체로 가져올 수 있습니까? –

관련 문제