Search code examples
objective-ckey-value-observing

NSMutableArray KVC/KVO question


This is a sample from book "Cocoa Programming For Mac Os X 3rd(HD)" chapter 7 "Key-Value Coding. Key-Vaule Observing

Here is the code:

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

And the sample works fine.(A blank table at first and you can add or delete record).

Now I tried to add some records to the array so that the blank table would have someting in it at first.

Here's what I'v tried(inside the init method):

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

But when I build and wrong I got the error msg:

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

Can any one help me out of here? Thanks in advance ^_^


Solution

  • That seems like a very reasonable response... you added NSData to your array named employees; guessing from the names, and from the KVC, you probably meant to add p1 to your array instead. So, try:

    [employees addObject:p1];