NSMutableArray KVC / KVO问题

时间:2011-02-12 08:57:19

标签: objective-c key-value-observing

这是“Mac OS X第三代(高清)可可编程”第7章“键值编码。键 - 值观察”一书中的一个样本

以下是代码:

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

任何人都可以帮助我离开这里吗?在此先感谢^ _ ^

1 个答案:

答案 0 :(得分:3)

这似乎是一个非常合理的回复...您将NSData添加到名为employees的数组中;从名称和KVC猜测,您可能想要将p1添加到您的数组中。所以,试试:

[employees addObject:p1];