可序列化的Objective-C类如下:
· NSArray
· NSMutableArray
· NSDictionary
· NSMutableDictionary
· NSData
· NSMutableData
· NSString
· NSMutableString
· NSNumber
· NSDate
上述类实例都可通过writeToFile:atomically:方法进行序列化。
属性列表非常方便,只要字典或数组仅包含特定可序列化的对象,就可以将NSDictionary和NSArray实例写入属性列表以及从属性列表创建它们。
但是对于自定义的类myClass,要使用属性列表序列化,有如下步骤:
1. 将每个字段中的值复制到NSDictionary实例中;
2. 将NSDictionary实例添加到另一个数组;
3. 将该数组写入属性列表文件。
显然,如果不做大量转换工作就根本不能为自定义类使用属性列表序列化。
#pragma mark -
#pragma mark 将以myClass为元素的数组转成以词典为元素
-(NSArray *)transformDataObjectToDic:(NSArray *)itemAry
{
if (itemAry == nil)
{
return nil;
}
NSMutableArray * dicMutAry = [NSMutableArray arrayWithCapacity:5];
// 获取数组,数组成员对应myClass的属性。
for (int i = 0 ; i<[itemAry count]; i++)
{
NSMutableDictionary * mutDic = [NSMutableDictionary dictionaryWithCapacity:5];
id item = [itemAry objectAtIndex:i];
NSArray * atrAry = [self traversalObjAtr:item];
if (atrAry != nil)
{
for (int j =0 ; j<[atrAry count]; j++)
{
NSString * keyStringByClassAtr = [atrAry objectAtIndex:j];
NSString * methodName = [NSString stringWithFormat:@"%@", keyStringByClassAtr];
if ([item respondsToSelector:NSSelectorFromString(methodName)])
{
NSString * artValue = [item performSelector:NSSelectorFromString(methodName) withObject:nil];
if (artValue != nil) {
[mutDic setObject:artValue forKey:keyStringByClassAtr];
}
}
}
}
[dicMutAry addObject:mutDic];
}
return dicMutAry;
}
#pragma mark -
#pragma mark 遍历并获取自定义类的各个字段
- (NSArray *)traversalObjAtr:(id)_class_object
{
NSMutableArray *itemMutAry = [[[NSMutableArray alloc] initWithCapacity:6] autorelease];
@synchronized(self) {
int i;
unsigned int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([_class_object class], &propertyCount);
for ( i=0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSString *propertyNameString = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
[itemMutAry addObject:propertyNameString];
thisProperty = nil;
}
free(propertyList);
}
return [[[NSArray alloc] initWithArray:itemMutAry] autorelease];
}