iOS属性列表序列化

可序列化的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];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值