I have a number of derived classes whose common base-class conforms to NSCoding
. I want to be able to easily encode an NSArray
holding instances of the various deriving classes.
@interface Base : NSObject <NSCoding>
@end
@interface DerivedSingleton : Base
+(instancetype) sharedInstance;
@end
@interface DerivedNonSingleton : Base
@end
The deriving singleton should have only one instance in the running system. It doesn't actually have any state to encode in the coder. It's instance is created with the +(void) initialize
class method.
DerivedSingleton *sharedInstance;
@implementation DerivedSingleton
+(void) initialize
{
sharedInstance = [DerivedSingleton new];
}
+(instancetype) sharedInstance
{
return sharedInstance;
}
@end
So, if I now make an array holding instances of the classes, and encode it:
NSArray *const array = @[
[DerivedSingleton sharedInstance],
[DerivedNonSingleton new],
[DerivedNonSingleton new]];
NSData *const arrayData = [NSKeyedArchiver archivedDataWithRootObject: array];
When I later decode it, I require references to the shared singleton to decode as references to the shared singleton…
NSArray *const decodedArray = [NSKeyedUnarchiver unarchiveObjectWithData: arrayData];
[decodedArray objectAtIndex: 0] == [DerivedSingleton sharedInstance];
I note that the NSCoding
protocol wants me to implement initWithCoder:
for the singleton, but during decode, I want this class to provide the shared instance, not a newly alloc
ed object.