Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Key Value Coding
swcng2001 Offline
Newbie
*

Posts: 1
Joined: Apr 2012
Post: #1
Key Value Coding
I'm another beginner trying to get my head round Cocoa and its intricacies. I was reading DeVoe's "Objective-C". In the section on Key Value Coding there are some examples of setValue:forKeyPath:. Somehow, try as I might I cannot get it to work.

The following is the code -

Code:
//
// Bar.h
// UsingKVC
//
// Created by Stephen Ng on 2/04/12.
// Copyright (c) 2012 Nutek. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Bar : NSObject
{
NSArray *array;
NSString *stringOnBar;
}
@property (retain,nonatomic) NSArray *array;
@property (retain,nonatomic) NSString *stringOnBar;
@end
Code:
@interface Foo : NSObject
{
Bar *bar;
NSString *stringOnFoo;
}
@property (retain,nonatomic) Bar *bar;
@property (retain,nonatomic) NSString *stringOnFoo;
@end
Code:
//
// Bar.m
// UsingKVC
//
// Created by Stephen Ng on 2/04/12.
// Copyright (c) 2012 Nutek. All rights reserved.
//

#import "Bar.h"

@implementation Bar
@synthesize array;
@synthesize stringOnBar;

@end

@implementation Foo

@synthesize bar;
@synthesize stringOnFoo;

@end
Code:
//
// main.m
// UsingKVC
//
// Created by Stephen Ng on 2/04/12.
// Copyright (c) 2012 Nutek. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Bar.h"

int main (int argc, const char * argv[])
{

@autoreleasepool {

Foo *foo = [[Foo alloc] init];
[foo setValue:@"blah blah" forKey:@"stringOnFoo"];
NSString *string = [foo valueForKey:@"stringOnFoo"];
NSLog(@"string: %@", string);

[foo setValue:@"The quick brown fox" forKeyPath:@"bar.stringOnBar"];
NSString *string2 = [foo valueForKeyPath:@"bar.stringOnBar"];
NSLog(@"string2: %@",string2);

}
return 0;
}
--------------

string2 is NULL!

I do not understand this. I understand that when using @property all the code becomes KVC compliant. Yet it seems the key path does not work.

Any help in learning this "beast" will be much appreciated.

Thanks.

Stephen
2012.04.03 12:42 AM
Find all posts by this user Quote this message in a reply
BeadiaDotNet Offline
Newbie
*

Posts: 1
Joined: May 2012
Post: #2
RE: Key Value Coding
The Foo object is probably not creating its Bar property. Add this:

Code:
- (id) init {
    [super init];
    bar = [[Bar alloc] init];
    return self;
}

- (void) dealloc {
    [bar release];
    [super dealloc];
}

...to Foo.m and you should be good to go.
2012.05.26 07:33 AM
Visit this user's website Find all posts by this user Quote this message in a reply
Post Reply 




User(s) browsing this thread: 1 Guest(s)