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標準。但似乎關鍵路徑不起作用。
完美。非常感謝。我假設[[Foo alloc] init]也會創建Bar對象! – swcng2001 2012-04-03 06:28:33