0

복잡한 C 구조를 가지고 있으며이 구조를 하나씩 NSDictionary로 변환하기가 어렵습니다. 이 C 구조를 NSNotificationCenter를 통해 게시하고 NSNotificationCenter 콜백 함수에서 다시 검색하려면 어떻게해야합니까? 제안 해 주시면 감사하겠습니다.NSNotificationCenter가 C 구조를 게시하고 알림 콜백 함수에서 다시 검색합니다.

+0

스틱'NSValue'의 구조체, 스틱 그 통지의'userInfo'에서 . – CodaFi

+0

@CodaFi 당신은 정말로 답변으로 게시해야합니다. – rmaddy

+0

@srjohnhuang 질문에 대한 답변이 충분합니까? 아니면 자세히 알고 싶습니까? – user3386109

답변

0

개인적으로 NSData에 구조체를 채우고 알림의 일부로 보내는 것이 가장 쉽습니다. 뒤에 오는 코드에서 사용 된 샘플 구조의 선언이 있습니다.

typedef struct 
{ 
    int a; 
    int b; 
} 
    ImportantInformation; 

다음은 알림의 일부로 구조를 보내는 코드입니다. 세 번째 줄의 마지막 부분은 NSData 객체를 NSDictionary에 넣고 해당 사전을 userInfo으로 전달합니다. 사전에있는 NSData의 키는 @ImportantInformation입니다.

ImportantInformation info = { 555, 321 }; 
NSData *data = [NSData dataWithBytes:&info length:sizeof(info)]; 
[[NSNotificationCenter defaultCenter] postNotificationName:@"ImportantChange" object:self userInfo:@{ @"ImportantInformation" : data }]; 

다음은 통지 관찰자를 추가하고 통지가 수신 될 때 실행되는 블록을 정의하는 코드입니다.

NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 

self.observer = [center addObserverForName:@"ImportantChange" 
            object:nil 
            queue:nil 
usingBlock:^(NSNotification *notif) 
{ 
    // this is the structure that we want to extract from the notification 
    ImportantInformation info; 

    // extract the NSData object from the userInfo dictionary using key "ImportantInformation" 
    NSData *data = notif.userInfo[@"ImportantInformation"]; 

    // do some sanity checking 
    if (!data || data.length != sizeof(info)) 
    { 
     NSLog(@"Well, that didn't work"); 
    } 
    else 
    { 
     // finally, extract the structure from the NSData object 
     [data getBytes:&info length:sizeof(info)]; 

     // print out the structure members to prove that we received that data that was sent 
     NSLog(@"Received notification with ImportantInformation"); 
     NSLog(@" a=%d", info.a); 
     NSLog(@" a=%d", info.b); 
    } 
}]; 

참고 : 특정 시점에서 반드시 관찰자를 제거하십시오.

[[NSNotificationCenter defaultCenter] removeObserver:self.observer]; 
+0

구체적인 예를 들어 주셔서 감사합니다. – srjohnhuang

1

저장 및 검색 NSValue 등

스토어 :

CustomStruct instanceOfCustomStruct = ...; 
NSValue * valueOfStruct = [NSValue valueWithBytes:&instanceOfCustomStruct objCType:@encode(CustomStruct)]; 

[[NSNotificationCenter defaultCenter] postNotificationName:@"YourNotification" object:self userInfo:@{@"CustomStructValue" : valueOfStruct}]; 

검색 :

NSValue * valueOfStruct = note.userInfo[@"CustomStructValue"]; 
CustomStruct instanceOfCustomStruct; 
[valueOfStruct getValue:&instanceOfCustomStruct]; 
+0

나는 당신의 솔루션을 시도해 보았고 또한 훌륭하게 작동합니다! 어쨌든 당신의 제안에 감사드립니다. – srjohnhuang