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

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

  • 相关阅读:
    代码对齐--string|stream
    pytest_30_40
    性能总结
    day41_IO模型
    postman_05_cookie_case_流(顺序)
    linux_压缩
    post_04_assert_请求参数预处理_pre_requests
    postman_网址
    postman_03_引用随机变量($guid,$timestamp,$randomInt)_and_参数引用外部文件
    CF 1354C2 思维
  • 原文地址:https://www.cnblogs.com/zsw-1993/p/4879559.html
Copyright © 2011-2022 走看看