In my app , i created my custom class and i am observing one of its property using KVO ,so that if its value changed it instantly display in firstview controller object (label or .. )
sample code
myCustomClass.h
@interface myCustomClass : NSObject {
NSString * text;
}
@property (nonatomic, retain) NSString * text;
- (void)changetext;
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";
}
firstViewController.h
@interface FirstViewController:UIViewController {
IBOutlet UILabel * label;
}
@property (nonatomic, retain) IBOutlet UILavel * label;
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];
}
but its not changing the data , can any one please tell me where i am wrong ?
thanks in advance
P.S : i wrote in hurry forgive me if any mistakes in writing and sorry for my bad english .
When you assign to an instance variable directly rather than going through a setter, you need to issue change notifications yourself with
willChangeValueForKey:anddidChangeValueForKey:. There’s no magic to variable assignment.