代码改变世界

iOS 多层级的immutable objects 转换成 mutable objects

2014-01-16 14:02  三戒1993  阅读(218)  评论(0编辑  收藏  举报

第一种方法是:将多层级的递归转换
方法;
+(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))

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