【发布时间】:2011-03-13 13:55:30
【问题描述】:
我正在尝试填充基于NSTableView 的文档并使用NSArrayController 控制它。我想我理解了Key Value coding 的概念。但是,我担心NSArrayController 不尊重Accessor Search Pattern for Ordered Collections。让我解释一下
我有一个定义的班级名称学生
#import <Cocoa/Cocoa.h>
@interface Student : NSObject {
NSString* studentName;
float marks;
}
//Accessor and mutators
@property (readwrite, copy) NSString* studentName;
@property (readwrite) float marks;
//Initializer - Init all resources
-(id) init;
//Dealloc - Release resources
-(void) dealloc;
@end
实现是
#import "Student.h"
@implementation Student
//Synthesize the accessors
@synthesize studentName;
@synthesize marks;
//Initializer - Init all resources
-(id) init
{
self = [super init];
if(self){
studentName = @"New Student";
marks = 0.0;
}
return self;
}
//Dealloc - Release resources
-(void) dealloc
{
[studentName release];
[super dealloc];
}
@end
MyDocument 类定义如下,其中包含一个NSMutableArray 类型的即时变量
#import <Cocoa/Cocoa.h>
@class Student;
@interface MyDocument : NSDocument
{
NSMutableArray* students;
}
//Initializers
-(id) init;
//Deallocators
-(void) dealloc;
//Creating the proxy object
-(id) mutableArrayValueForKey:(NSString *)key;
//Array controller uses keyvalue
//coding to call this
-(void) insertObject:(Student*) s inStudentsAtIndex:(int) index;
@end
在 IB 中,Array Controller 的属性设置为 Student 对象,并将其实例变量添加到键中。在绑定部分,Content Array 绑定到 File Owner's,它是 MyDocument 类的一个实例。模型键路径设置为数组名students
这里是MyDocument的实现
#import "MyDocument.h"
#import "Student.h"
@implementation MyDocument
- (id)init
{
self = [super init];
if (self) {
students = [[NSMutableArray alloc] init];
}
return self;
}
-(void) dealloc
{
[students release];
[super dealloc];
}
//Array controller uses keyvalue
//coding to call this
-(void) insertObject:(Student*) s inStudentsAtIndex:(int) index
{
NSLog(@"Insert object is called");
}
//Creating the proxy object
-(id) mutableArrayValueForKey:(NSString *)key
{
NSLog(@"Checking if NSArrayController is trying to create a proxy %@",key);
return students;
}
我的问题-(void) insertObject:(Student*) s inStudentsAtIndex:(int) index 永远不会被调用。但是,如果我实现一个函数名-(void) setStudents:(Student*)s,就会调用它。 -(id) mutableArrayValueForKey:(NSString *)key 仅用于调试目的;我想看看 Key Value 编码的某些部分是否有效。无论有无 -(id) mutableArrayValueForKey:(NSString *)key
我错过了什么?我在 Mac 10.6.6 上使用 XCode 3.2.5
【问题讨论】:
标签: objective-c macos