Нужно добавить наблюдателя NSDistributedNotification в мой проект Firebreath.

Мне нужно отправить распределенное уведомление из моего приложения какао в мой проект firebreath, поэтому мне нужно создать наблюдателя и селектор в моем коде firebreath. Я изменил расширение класса на «.mm», чтобы поддерживать код Objective-C. У меня уже есть код Objective-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: ошибка: «я» не было объявлено в этой области.

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


person Ana    schedule 30.12.2011    source источник


Ответы (2)


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

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

person taxilian    schedule 30.12.2011
comment
В кодовой базе firebreath есть несколько примеров использования объектов target c с firebreath. - person taxilian; 31.12.2011

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

#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];
person Ana    schedule 03.01.2012
comment
Если я удалю эту строку [my_project release]; уведомление работает, но мне нужно освободить память. Я тоже не могу сделать автозапуск. Любые идеи? - person Ana; 03.01.2012