2011-02-12 71 views
0

這是本書「可可規劃爲Mac OS X 3(HD)」第7章的樣本「鍵 - 值編碼鍵 - Vaule觀察NSMutableArray的KVC /志願問題

下面是代碼:

Person.h:

#import <Foundation/Foundation.h> 


@interface Person : NSObject { 
    NSString *personName; 
    float expectedRaise; 
} 
@property (readwrite, copy) NSString *personName; 
@property (readwrite) float expectedRaise; 

@end 

Person.mm:

#import "Person.h" 
@implementation Person 

@synthesize expectedRaise; 
@synthesize personName; 

- (id)init 
{ 
    [super init]; 
    expectedRaise = 0.05; 
    personName = @"New Person"; 
    return self; 
} 

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

@end 

MyDocument.h:

#import <Cocoa/Cocoa.h> 

@interface MyDocument : NSDocument 
{ 
    NSMutableArray *employees; 
} 

@property (retain) NSMutableArray *employees; 

@end 

MyDocument.mm:

#import "MyDocument.h" 
#import "Person.h" 

@implementation MyDocument 

@synthesize employees; 

- (id)init 
{ 
    if (![super init]) 
     return nil; 

    employees = [[NSMutableArray alloc] init]; 

    return self; 
} 
- (void)dealloc 
{ 
    [employees release]; 
    [super dealloc]; 
} 

- (void)windowControllerDidLoadNib:(NSWindowController *) aController 


@end 

和採樣工作正常(空白表,在第一,你可以添加或刪除記錄)。

現在我試着給數組添加一些記錄,這樣空白表首先會有 。

這裏就是我心中已經嘗試過(裏面的init方法):

[self willChangeValueForKey:@"employees"]; 
Person *p1 = [[Person alloc] init]; 
[employees addObject: [NSData dataWithBytes: &p1 length: sizeof(p1)]]; 
[self didChangeValueForKey:@"employees"]; 

但是當我建立和錯了,我得到了錯誤信息:

[<NSConcreteData 0x422bf0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key personName. 
...... 

任何一個可以幫助我的這裏?在此先感謝^ _^

回答

3

這似乎是一個非常合理的響應...您將NSData添加到您的陣列名爲employees;從名字和KVC猜測,你可能意味着將p1添加到你的數組中。因此,請嘗試:

[employees addObject:p1]; 
+1

另外,不要忘記在將數組添加到數組後,將p1釋放(除非當然,您仍然可以使用它)。 – puzzle 2011-02-12 15:01:57