Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import <Foundation/Foundation.h>
- @interface Character : NSObject
- {
- NSString *characterName;
- NSInteger ownedClowCards;
- }
- @property (nonatomic, copy) NSString *characterName;
- @property NSInteger ownedClowCards;
- -(void)hasLostClowCard;
- -(void)hasGainedClowCard;
- @end
- @implementation Character
- @synthesize characterName;
- @synthesize ownedClowCards;
- -(void)hasLostClowCard
- {
- NSLog(@"%@ has lost a card! Cards now: %ld", characterName, ownedClowCards);
- }
- -(void)hasGainedClowCard
- {
- NSLog(@"%@ has earned a card! Cards now: %ld", characterName, ownedClowCards);
- }
- -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
- if([keyPath isEqualToString:@"ownedClowCards"])
- {
- NSInteger oldC = [change objectForKey:NSKeyValueChangeNewKey];
- NSInteger newC = [change objectForKey:NSKeyValueChangeOldKey];
- if(oldC < newC)
- {
- [self hasLostClowCard];
- }else
- {
- [self hasGainedClowCard];
- }
- }
- }
- @end
- int main()
- {
- Character *sakura;
- Character *shaoran;
- //Create and give the properties some values with KVC...
- sakura = [[Character alloc] init];
- [sakura setValue:@"Sakura Kinomoto" forKey:@"characterName"];
- [sakura setValue:[NSNumber numberWithInt:20] forKey:@"ownedClowCards"];
- shaoran = [[Character alloc] init];
- [shaoran setValue:@"Li Shaoran" forKey:@"characterName"];
- [shaoran setValue:[NSNumber numberWithInt:21] forKey:@"ownedClowCards"];
- //Done! Now we are going to fetch the values using KVC.
- NSString *mainCharacter = [sakura valueForKey:@"characterName"];
- NSNumber *mainCharCards = [sakura valueForKey:@"ownedClowCards"];
- NSString *rival = [shaoran valueForKey:@"characterName"];
- NSNumber *rivalCards = [shaoran valueForKey:@"ownedClowCards"];
- NSLog(@"%@ has %d Clow Cards", mainCharacter, [mainCharCards intValue]);
- NSLog(@"%@ has %d Clow Cards", rival, [rivalCards intValue]);
- //---------------------------------------------------------------------
- // Here begins the KVO section.
- [sakura addObserver:sakura forKeyPath:@"ownedClowCards" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; //Sakura is observing her own Clow Cards.
- [sakura setValue:[NSNumber numberWithInt:22] forKey:@"ownedClowCards"];
- [sakura removeObserver:sakura forKeyPath:@"ownedClowCards"];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement