2012-04-03 4 views
1

私はココアとその複雑さの中で私の頭の中で頭を上げようとしている別の初心者です。私はDeVoeの "Objective-C"を読んでいました。キーバリューコーディングのセクションでは、setValue:forKeyPath:のいくつかの例があります。どういうわけか、私はそれを働かせることができないかもしれないようにしてください。setValue:forKeyPathとvalueForKeyPathを使うにはどうすればいいですか?

次のコードです:

// 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 


@interface Foo : NSObject 
{ 
    Bar *bar; 
    NSString *stringOnFoo; 
} 
@property (retain,nonatomic) Bar *bar; 
@property (retain,nonatomic) NSString *stringOnFoo; 
@end 

// 
// 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 

// 
// 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のはNULLです!

私はこれを理解していません。 @propertyを使用すると、すべてのコードがKVCに準拠するようになります。しかし、鍵の道が働かないようです。

答えて

3

foo.barはゼロではない(あなたはbarの値を設定していない)ので、KVCアクセサは黙って失敗するか、nilを返す。キーパスメッセージの値は基本的に別のアクセサに分解され、パスが完了しません。

新しいBarオブジェクトを作成し、foo.barに割り当てると、キーパスコードが機能します。

+0

パーフェクト。どうもありがとう。私は[[Foo alloc] init]もBarオブジェクトを作成すると仮定していました! – swcng2001

関連する問題