【问题标题】:NSMutableArray KVC/KVO questionNSMutableArray KVC/KVO 问题
【发布时间】:2011-02-12 08:57:18
【问题描述】:

这是《Cocoa Programming For Mac Os X 3rd(HD)》第 7 章“Key-Value Coding. Key-Vaule Observing”一书中的示例

代码如下:

Person.h:

 #import <Foundation/Foundation.h>


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

 @end

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

我的文档.h:

#import <Cocoa/Cocoa.h>

@interface MyDocument : NSDocument
{
    NSMutableArray *employees;
}

@property (retain) NSMutableArray *employees;

@end

我的文档.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.
......

谁能帮我离开这里?提前谢谢^_^

【问题讨论】:

    标签: objective-c key-value-observing


    【解决方案1】:

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

    [employees addObject:p1];
    

    【讨论】:

    • 另外,不要忘记在将 p1 添加到数组后释放它(当然,除非你仍然会使用它)。
    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    相关资源
    最近更新 更多