我正在尝试在我的 OS X 应用程序中保存用户首选项。我有一个 NSTableView,它将其数据存储到我的.plist
文件中,但是我无法将相同的数据加载回我的 NSTableView。
我的模型对象:
#import <Foundation/Foundation.h>
@interface UserKeys : NSObject <NSCoding>
@property (nonatomic, copy) NSString *userKeyName;
@property (nonatomic, copy) NSString *userApi;
@property (nonatomic, copy) NSString *userCode;
@end
及其实施:
#import "UserKeys.h"
@implementation UserKeys
- (id)init
{
self = [super init];
if (self) {
//
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.userKeyName = [aDecoder decodeObjectForKey:@"userKeyName"];
self.userApi = [aDecoder decodeObjectForKey:@"userApi"];
self.userCode = [aDecoder decodeObjectForKey:@"userCode"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)enCoder {
[enCoder encodeObject:self.userKeyName forKey:@"userKeyName"];
[enCoder encodeObject:self.userApi forKey:@"userApi"];
[enCoder encodeObject:self.userCode forKey:@"userCode"];
}
@end
我的首选项视图控制器标题:
#import <Cocoa/Cocoa.h>
#import "MASPreferencesViewController.h"
#import "UserKeys.h"
@interface PreferencesApiKeysViewController : NSViewController <MASPreferencesViewController>
@property (strong) NSMutableArray *allKeys;
@end
及其实施:
#import "PreferencesApiKeysViewController.h"
#import "UserKeys.h"
@interface PreferencesApiKeysViewController ()
@property (weak) IBOutlet NSTableView *keysTableView;
@end
@implementation PreferencesApiKeysViewController
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle {
if ((self = [super initWithNibName:nibName bundle:bundle])) {
self.allKeys = [NSMutableArray array];
}
return self;
}
// delegating....
//
- (void)viewWillAppear {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"UserKeys"];
if (data != nil) {
NSArray *oldArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (oldArray != nil) {
self.allKeys = [[NSMutableArray alloc] initWithArray:oldArray];
} else {
self.allKeys = [NSMutableArray array];
}
}
}
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
// some code...
return cellView;
}
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
return [self.allKeys count];
}
我得到的错误是:
-[UserKeys count]: unrecognized selector sent to instance 0x100534df0
当我在 中放置断点时- (void)viewWillAppear
,我可以看到它data
有大约 250 个字节,但这oldArray
似乎是空的。我知道我在这里犯了一些重大错误,self.allKeys
因此我的表不知道它应该创建多少行,但是在多次尝试获取正确的数据之后,我真的不知道为什么会发生这种情况。
那么,如何正确地取消归档我的数据并将其呈现在 NSTableView 中?
(我使用的是 Xcode 4.6)