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))

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

  • 相关阅读:
    源码分析:Java对象的内存分配
    源码分析:Java堆的创建
    Java Main如何被执行?
    HotSpot模板解释器目标代码生成过程源码分析
    Java常量池解析与字符串intern简介
    Java类的连接与初始化 (及2013阿里初始化笔试题解析)
    css中对position的几种定位方式的最佳诠释
    DB2学习笔记
    three.js:Failed to execute 'texImage2D' on 'WebGLRenderingContext解决方案
    线程隔离ThreadLocal
  • 原文地址:https://www.cnblogs.com/zsw-1993/p/4879559.html
Copyright © 2011-2022 走看看