[ios]从Framework或自定义静态库向Target Application添加观察者

时间:2017-01-07 21:23:29

标签: ios objective-c frameworks observer-pattern

我开发了一个ios lib/framework,我记录用户登录并连接到服务器并实时从服务器获取数据。 在同一个library/framework中,我想将观察者添加到我的应用程序中,以便我知道应用程序何时进入后台或再次变为活动状态。

类似于我们通常在应用程序代码本身中执行的操作....(我的测试应用程序代码如下。我希望移动到公共lib/framework的观察者功能)

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(MyAppWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];

但即使我已将方法定义为

void MyAppWillResignActive(id self, SEL _cmd, id application) {
    NSLog(@"%s", __PRETTY_FUNCTION__);
}

1 个答案:

答案 0 :(得分:0)

注意选择器MyAppWillResignActive中要调用的方法的签名。

编辑:按照iosDeveloper09评论中的建议将注册移至库初始化。

班级

  • initialize

    期间注册
    + (void)initialize {
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(applicationWillResignActive:)
         name:UIApplicationWillResignActiveNotification
         object:nil];
    }
    
  • 类处理程序+

    + (void)applicationWillResignActive:(NSNotification *)notification
    

实例级别

  • init

    期间注册
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            [[NSNotificationCenter defaultCenter]
             addObserver:self
             selector:@selector(applicationWillResignActive:)
             name:UIApplicationWillResignActiveNotification
             object:nil];
        }
        return self;
    }
    
  • 实例处理程序-

    - (void)applicationWillResignActive:(NSNotification *)notification
    

主机

@property (nonatomic, retain) SO_41526719Library * lib;

// Keep an instance around
self.lib = [[SO_41526719Library alloc] init];

在运行时

  

applicationWillResignActive NSConcreteNotification 0x6000000545e0 {name = UIApplicationWillResignActiveNotification; object =}