Нужно добавить наблюдателя NSDistributedNotification в мой проект Firebreath - PullRequest
0 голосов
/ 30 декабря 2011

Мне нужно отправить распределенное уведомление из моего приложения с какао в мой проект Firebreath, поэтому мне нужно создать наблюдателя и селектор в моем коде Firebreath. Я изменил расширение класса на ".mm", чтобы поддерживать код target-c. У меня уже есть код target-c в моем проекте Firebreath, и он работает нормально. Но когда я пытаюсь создать наблюдателя, в моем коде появляются ошибки, и я не знаю, как их решить.

Вот мой исходный код из проекта Firebreath:

//This is the selector 
- (void)receiveAppConfirmationNotification:(NSNotification*)notif{
    //The application is alive.
    NSLog(@"The application is alive!!!!!!!!");
}

std::string MyProjectAPI::bgp(const std::string& val)
{       
    //Add an observer to see if the application is alive.
    NSString *observedObject = @"com.test.net";
    NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
    [center addObserver: self
               selector: @selector(receiveAppConfirmationNotification:)
                   name: @"App Confirmation Notification"
                 object: observedObject];
}

Вот мои ошибки:

... firebreath /../ projects / MyProject / MyProjectAPI.mm: 133: ошибка: ожидаемый неквалифицированный идентификатор перед токеном '-'. В этой строке я определил метод receiveAppConfirmationNotification.

... firebreath /../ projects / MyProject / MyProjectAPI.mm: 157: ошибка: «self» не было объявлено в этой области.

Как я могу определить селектор? Как я могу добавить наблюдателя в качестве самого класса?

Ответы [ 2 ]

0 голосов
/ 03 января 2012

Я сделал интерфейс и реализацию, а код без ошибок. Проблема в том, что я могу отправлять уведомления в свое приложение какао, но не могу получить уведомление от приложения к плагину. Вот заголовочный файл:

#ifdef __OBJC__

@interface FBMyProject : NSObject {
    NSString *parameter_val;
}

@property (nonatomic, retain) NSString *parameter_val;

-(void) receiveAppConfirmationNotification:(NSNotification*)notif;

@end
#endif

class MyProjectAPI : public FB::JSAPIAuto
{
    public:
    ...
}
#endif

Вот мой исходный файл:

@implementation FBMyProject
@synthesize parameter_val;

  -(void) receiveAppConfirmationNotification:(NSNotification*)notif{
       //The application is alive.
       NSLog(@"The application is alive!!!!!!!!");
   }

  - (id)init
  {
      self = [super init];
      if (self) {
          NSString *observedObject = @"test.com";
          NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
          [center addObserver: self
                     selector: @selector(receiveAppConfirmationNotification:)
                         name: @"App Confirmation Notification"
                       object: observedObject];

      }
      return self;
  }

  - (void)dealloc
  {
      // unregister notification
      [[NSDistributedNotificationCenter defaultCenter] removeObserver: self 
                                                                 name: @"App Confirmation Notification"
                                                               object: nil];

      [self.parameter_val release];
      [super dealloc];
  }
@end



std::string MyProjectAPI::bgp(const std::string& val)
{       
    FBMyProject *my_project = [[FBMyProject alloc] init];
    my_project.parameter_val = [NSString stringWithUTF8String:val.c_str()];
    [my_project release];

    return val;
}

Вот мой источник из приложения какао:

NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
                      @"OK", @"confirmation", 
                      nil];

//Post the notification
NSString *observedObject = @"test.com";
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center postNotificationName: @"App Confirmation Notification"
                      object: observedObject
                    userInfo: data
          deliverImmediately: YES];
0 голосов
/ 30 декабря 2011

Селектор должен быть частью класса target-c ++;вы не можете просто бросить его в никуда, это должно быть в разделе @implementation класса.

Чтобы все было как можно более совместимым, я рекомендую помещать разделы @interface и @implementationв файле .mm, чтобы файл .h был совместим с C ++, но это решать вам;это будет проще, если вы сделаете это таким образом.Вы можете использовать шаблон pimpl, чтобы помочь с этим, если хотите.

...