我想填充一個基於NSTableView
的文檔,並使用NSArrayController
來控制它。我想我理解了Key Value coding的概念。不過,我擔心NSArrayController
不符合Accessor Search Pattern for Ordered Collections。讓我來解釋NSArrayController和關鍵值編碼
我定義一個類名學生
#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中,設置了陣列控制器的屬性Student對象及其實例變量添加到密鑰中。在綁定部分中,Content Array綁定到File Owner,它是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
這工作! – GarryO 2011-03-19 16:28:54
我讀了這3到4次,我告訴自己:「這不是我的問題,不是!我不會這麼做!」 ...但這正是我的問題。謝謝! – Jeff 2013-06-28 19:23:01