NSKeyedArchiver returning unexpected class?

依然范特西╮ 提交于 2019-12-12 12:10:05

问题


I have a custom class that extends NSString. I'm attempting to serialize it (for drag/drop) using an NSKeyedArchiver. The class overrides the ...Coder methods:

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        data = [[aDecoder decodeObjectForKey:@"data"] copy];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:self.data forKey:@"data"];
}

But when I try to actually run through the archiving/unarchiving:

MyClass *object = [[MyClass alloc] init];
[pboard setData:[NSKeyedArchiver archivedDataWithRootObject:object] forType:SACP_WRAPPER_DRAG_TYPE];
NSLog(@"Wrote data for class %@", [object class]);

...

id item = [NSKeyedUnarchiver unarchiveObjectWithData:[[info draggingPasteboard] dataForType:SACP_WRAPPER_DRAG_TYPE]];
NSLog(@"Read data for class %@", [item class]);

The output is not what I am expecting:

2011-10-15 18:56:22.898 MyApp[7402:707] Wrote data for class ASCIIString
2011-10-15 18:56:23.345 MyApp[7402:707] Read data for class __NSCFString

回答1:


NSString is a class cluster:

"NSString is a class cluster, along with other Foundation types such as NSNumber and NSArray:

Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private, concrete subclasses under a public, abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness. Class clusters are based on the Abstract Factory design pattern discussed in “Cocoa Design Patterns.”"

Make sure you read the 'Subclassing Notes' in the NSString doc... you have to implement a custom storage mechanism for your subclass. My guess is that you aren't doing this, or if you are, you are still seeing those private classes pop up when you call the NSCoding methods on super, because super will use the methods of the specific private class that the NSString refers to (which depends on its contents).



来源:https://stackoverflow.com/questions/7781248/nskeyedarchiver-returning-unexpected-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!