我在屏幕的UIViewController上用NULL初始化了一个对象。 对象将在运行库中获取他的值。 我想观察这个对象,当它得到值时,我想对它运行另一个方法。 我在考虑在事件不是更空的时候激发它,然后在类的某个地方列出它,但是我不知道怎么做,或者这是不是一个好主意。 谢了。
如果可以使用属性执行此操作,请尝试
@interface ...
@property (nonatromic,strong) SomeObject * obj;
@end
@implementation ...
// Setter of obj
// You can do this for all properties of course
- ( void ) setObj:( SomeObject * ) obj
{
// Some logic e.g.
if ( obj.x > 100 )
{
self.label.hidden = YES;
}
else if ( obj.x > 200 )
{
self.label.text = @"Too much";
}
// Here the setting takes place
_obj = obj; // Here _obj is the member and obj the new value
}
// Just for reference, this is the getter
- ( SomeObject * ) obj
{
// Even here you can add logic, e.g.
if ( ! _obj )
{
_obj = [SomeObject alloc] initSomeDefault];
}
return _obj;
}
这是相当标准的Objective-C的东西。 查找一些参考文献,因为这通常用于嵌入一些逻辑,并且比KVO更容易。 也就是说,KVO是非常强大的。
这里有另一个建议,为什么不使用nsnotification
。 然后,无论何时设置对象,您都可以在setter内部发布通知,您可以在任何地方侦听该通知并采取适当的操作。 这也经常被用来听键盘什么时候出现。