NSKeyedArchiver不保存对象的所有属性

时间:2011-05-17 05:23:50

标签: objective-c cocoa nskeyedarchiver

我遇到了一个问题,我正在保存一个具有颜色和标签属性的“节点”(下面的标题)数组。当它保存在 - (void)saveDataToDiskWithPath:(NSURL *)路径中时,日志显示这些属性存在。当我稍后从保存的文件中再次加载数组时,节点的框架仍然存在,但是数组中的每个节点都丢失了它的标签和颜色......任何想法为什么?我能做错什么?也许我只是累了,以后都会有意义......

Node.h:

//
//  Node.h
//

#import <Cocoa/Cocoa.h>


@interface Node : NSView {
@private
    NSColor *thisColor;
    NSColor *originalColor;
    NSRect dragRect;
    BOOL msDn;
    long tag;
    BOOL amSelected;
}

@property long tag;
@property (nonatomic, retain) NSColor* originalColor;

- (id)initWithFrame:(NSRect)frame andColor:(NSColor*)color;
- (void)select:(BOOL)yesOrNo;

@end

保存方法:

- (void) saveDataToDiskWithPath:(NSURL*)path
{
    NSLog(@"Path is %@", [path absoluteString]);
    NSMutableDictionary * rootObject;
    rootObject = [NSMutableDictionary dictionary];
    for(Node* node in [sharedValues nodes]){
        NSLog(@"Node has color %@ and tag %ld.", [node originalColor], [node tag]);
    }
    [rootObject setValue: [imageView aPath] forKey:@"path"];
    [rootObject setValue:[sharedValues nodes] forKey:@"nodes"];
    [NSKeyedArchiver archiveRootObject: rootObject toFile: [path path]];
}

加载方法:

- (void)loadDataFromDiskWithPath:(NSURL*)path
{
    NSDictionary * rootObject;

    rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:[path path]];    
    [imageView setAPath:[rootObject valueForKey:@"path"]];
    [sharedValues setNodes:[rootObject valueForKey:@"nodes"]];
    [imageView setNeedsDisplay:YES];
}

1 个答案:

答案 0 :(得分:2)

您必须采用NSCoding协议并实施-initWithCoder:-encodeWithCoder:方法才能正确归档对象。由于Node是采用协议的UIView的子类,因此它的某些部分正在正确存档。这些是UIView及其父类的属性。为确保正确归档,Node还必须实现协议。通过this doc获取更多信息。