zoukankan      html  css  js  c++  java
  • iOS 多层级的immutable objects 转换成 mutable objects

    第一种方法是:将多层级的递归转换
    方法;
    +(id) recursiveMutable:(id)object
    {
    if([object isKindOfClass:[NSDictionary class]])
    {
    NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:object];
    for(NSString* key in [dict allKeys])
    {
    [dict setObject:[App recursiveMutable:[dict objectForKey:key]] forKey:key];
    }
    return dict;
    }
    else if([object isKindOfClass:[NSArray class]])
    {
    NSMutableArray* array = [NSMutableArray arrayWithArray:object];
    for(int i=0;i<[array count];i++)
    {
    [array replaceObjectAtIndex:i withObject:[App recursiveMutable:[array objectAtIndex:i]]];
    }
    return array;
    }
    else if([object isKindOfClass:[NSString class]])
    return [NSMutableString stringWithString:object];
    return object;
    }


    测试:
    NSDictionary* testDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObject:@"Test" forKey:@"Key"],@"A",[NSArray arrayWithObjects:@"1",[NSNumber numberWithInt:2],@"3",nil],@"B",@"Test String",@"C",nil];
    NSMutableDictionary* testMutableDict = [App recursiveMutable:testDict];
     
    // Test A
    [[testMutableDict objectForKey:@"A"] setObject:@"Test2" forKey:@"Key2"];
    [[[testMutableDict objectForKey:@"A"] objectForKey:@"Key"] appendString:@" -- This Works"];
    // Test B
    [[testMutableDict objectForKey:@"B"] addObject:@"4"];
    // Test C
    [[testMutableDict objectForKey:@"C"] appendString:@" - Just testing NSMutableString again"];
    NSLog(@"testMutableDict = %@",testMutableDict);
    结果:
    testMutableDict = { A = { Key = “Test — This Works”; Key2 = Test2; }; B = ( 1, 2, 3, 4 ); C = “Test String – Just testing NSMutableString again”; }


    第二种:
    使用coreFoundation框架里的CFPropertyListCreateDeepCopy,使用选项kCFPropertyListMutableContainersAndLeaves,意思是深度mutable
    非ARC使用:
    NSArray *immutableArray = [JSON objectForKey:@"result"];
    self.myMutableArray = [(NSMutableArray *)CFPropertyListCreateDeepCopy(NULL, immutableArray, kCFPropertyListMutableContainersAndLeaves) autorelease];
    ARC使用:
    CFBridgingRelease(CFPropertyListCreateDeepCopy(NULL, (__bridge CFPropertyListRef)(immutableArray), kCFPropertyListMutableContainersAndLeaves))

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Zepto swipe 无效(坑)
    Zepto.js-Ajax 请求
    Zepto.js-事件处理
    excel 大文件解析原理实现
    springboot 集成J2Cache
    springboot 单元测试 指定启动类
    springboot 解决 数字长度过长导致JS精度丢失问题
    JS 基本操作
    VUE 动态菜单管理
    VUE router-view key 属性解释
  • 原文地址:https://www.cnblogs.com/zsw-1993/p/4879559.html
Copyright © 2011-2022 走看看