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

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

  • 相关阅读:
    团队冲刺第五天
    团队冲刺第四天
    学习进度条---第八周
    团队冲刺第三天
    团队冲刺第二天
    团队冲刺第一天
    学习进度条--第七周
    课堂练习--第7周(两人结对)
    学习进度条--第六周
    第一次 在Java课上的编程
  • 原文地址:https://www.cnblogs.com/zsw-1993/p/4879559.html
Copyright © 2011-2022 走看看