I have Objective-C class that has C array property.
And I want to serialize the property with NSCoding.
@interface TestClass : NSObject <NSCoding>
@property (nonatomic) int* intArray;
@end
@implementation TestClass
-(instancetype)init
{
self = [super init];
if (self) {
_intArray = (int *)malloc(sizeof(int) * 5);
for (int i = 0; i < 5; i++) {
_intArray[i] = 0;
}
}
return self;
}
-(void)dealloc
{
free(_intArray);
}
-(instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
//???
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)coder
{
//???
}
@end
What should I write in ???.
Thank you.
EDIT:
Thank you for answers.
But Which should I use decodeArrayOfObjCType:count:at: or NSData?
If I don't know count of array, I cannot use decodeArrayOfObjCType:count:at: method?
-(instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
_itemCount = [coder decodeIntForKey:kItemCount];
_intArray = (int *)malloc(sizeof(int) * _itemCount);
[coder decodeArrayOfObjCType:@encode(int) count:_itemCount at:_intArray];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeInt:_itemCount forKey:kItemCount];
[coder encodeArrayOfObjCType:@encode(int) count:_itemCount at:_intArray];
}
or
-(instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
_itemCount = [coder decodeIntForKey:kItemCount];
NSData *data = [coder decodeObjectForKey:kIntArray];
if (data) {
NSUInteger length = [data length];
_intArray = (int *)malloc(length);
[data getBytes:_intArray length:length];
}
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeInt:_itemCount forKey:kItemCount];
if (_intArray) {
NSData *data = [NSData dataWithBytes:_intArray length:sizeof(int) * _itemCount];
[coder encodeObject:data forKey:kIntArray];
}
}
Thank you.
If you don't know how many values are in the array at the time of decoding, then you might want to use
NSData
. So, you might have two properties, one for theintData
, but another for thecount
of items in the array:Or, if you didn't want to use
NSData
, you could useencodeBytes:length:forKey:
:The Encoding and Decoding C Data Types of the Archives and Serializations Programming Guide outlines some additional considerations: