单身和KVO的问题

app*_*eDE 2 iphone objective-c ios4

在我的应用程序中,我创建了我的自定义类,我正在使用KVO观察其属性之一,因此如果其值发生更改,它会立即显示在firstview控制器对象(标签或...)中

示例代码

myCustomClass.h

@interface myCustomClass : NSObject {
    NSString * text;
}
@property (nonatomic, retain) NSString * text;
- (void)changetext;
Run Code Online (Sandbox Code Playgroud)

myCustomClass.m

@implementation myCustomClass

@synthesize text;
static myCustomClass * _sharedInstance;

- (id)init
{
    if ((self = [super init])) {
        text = @ "";
    }
    return self;
}

+ (myCustomClass *)sharedInstance
{
    if (!_sharedInstance) {
        _sharedInstance = [[myCustomClass alloc] init];
    }

    return _sharedInstance;
}
- (void)changetext {
    text = @ "changed";
}
Run Code Online (Sandbox Code Playgroud)

firstViewController.h

@interface FirstViewController:UIViewController {

    IBOutlet UILabel * label;
}
@property (nonatomic, retain) IBOutlet UILavel * label;
Run Code Online (Sandbox Code Playgroud)

firstviewController.m

@implementation FirstViewController

@synthesize label;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id) object change:(NSDictionary *)change context:(void *)context
{
    label.text = [change valueForKey:@ "new"];
}
- (void)viewDidLoad {
    myCustomClass * myEngine = [myCustomClass sharedInstance];
    [myEngine addObserver : self forKeyPath : @ "text" options : NSKeyValueObservingOptionNew context : nil];
    [myEngine changetext];

    [super viewDidLoad];
}
Run Code Online (Sandbox Code Playgroud)

但它没有改变数据,任何人都可以告诉我哪里错了?

提前致谢

PS:我写信匆匆原谅我,如果有任何写作错误,抱歉我的英语不好.

Chu*_*uck 5

当您直接分配实例变量而不是通过setter时,您需要使用willChangeValueForKey:和自己发出更改通知didChangeValueForKey:.变量赋值没有神奇之处.


小智 5

替换textself.textas将观察者子系统绑定到作为属性合成的getter和setter方法中.