我有两个ViewControllers
我需要将NSMutableDictionary传递给第二个,但是这样做的正确方法是什么?
NSMutableDictionary在第一个视图中被修改并传递给第二个,它没有被修改
方法1
- First
@property (nonatomic, retain) NSMutableDictionary * results1;
- Second
@property (nonatomic, retain) NSMutableDictionary * results2;
in First IBAction when iam going to push the second
{
SecondViewController * svc = [[SecondViewController alloc] init];
//svc.results2 is not initialized in Second
svc.2results = [[NSMutableDictionary alloc] init];
svc.2results = [self.results1 mutableCopy];
//in second view did unload i call [results2 release];
[self.navigationController pushViewController:svc animated:YES];
[svc release];
}
方法2
- First
@property (nonatomic, retain) NSMutableDictionary * results1;
- Second with COPY
@property (nonatomic, copy) NSMutableDictionary * results2;
{
SecondViewController * svc = [[SecondViewController alloc] init];
//svc.results2 is not initialized in Second
svc.results2 = [self.results1 mutableCopy];
//in second view did unload i call [results2 release];
[self.navigationController pushViewController:svc animated:YES];
[svc release];
}
答案 0 :(得分:4)
都不是。在方法1中,您泄漏了2个NSMutableDictionary实例,而在方法2中,您正在泄漏其中一个实例
方法1中的代码完全没有意义。如果你想让x值为2,你会写x = 1; x = 2;
吗?我对此表示怀疑,为什么要用物体呢?
使用@property
个变体,您可以使用:
SecondViewController * svc = [[SecondViewController alloc] init];
//svc.results2 is not initialized in Second
svc.results2 = [[self.results1 mutableCopy] autorelease];
//in second view did unload i call [results2 release];
[self.navigationController pushViewController:svc animated:YES];
[svc release];
并且您应该将ViewController2中的NSMutableDictionary
替换为NSDictionary
,将mutableCopy
替换为copy
,您不需要修改它,也不需要在第一名..
如果你使用copy属性,则不需要先使用(可变)复制。你要复制两次。
这是不必要的,但只要你使用适当的内存管理它就不会受到伤害。
编辑:漏洞:
svc.2results = [[NSMutableDictionary alloc] init];
^ retain +1 ^^^^^ retain + 1 = retain + 2
svc.2results = [self.results1 mutableCopy];
^ retain +1 ^^^^^^^^^^^ retain + 1 = retain + 2
但在svc
中你只释放(retain - 1)一次(第二个setter实际上释放了第一个对象,但只有一次释放)。所以两者都将永远留在记忆中。
没有泄漏:
svc.2results = [[self.results1 mutableCopy] autorelease];
^ retain +1 ^^^^^^^^^ +1 ^^^^^^^^^^^ -1 later = retain + 1
并且您将在svc
中释放(retain - 1),该对象将不再保留,并且将被取消分配。