怎样的NSMutableDictionary传递到另一个视图控制器

问题描述:

我有两个ViewControllers怎样的NSMutableDictionary传递到另一个视图控制器

我需要一个的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]; 
} 

都不是。在方法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与NSDictionarymutableCopycopy取代NSMutableDictionary,你不想修改它,没必要使可变首先..

如果您使用复制属性没有必要先使用(可变)复制。你正在复制两次。
这是没有必要的,但只要你使用适当的内存管理,它不会伤害。


编辑:泄漏:

svc.2results = [[NSMutableDictionary alloc] init]; 
^retain +1      ^^^^^ retain + 1  = retain + 2 
svc.2results = [self.results1 mutableCopy]; 
^retain +1    ^^^^^^^^^^^ retain + 1  = retain + 2 

svc你释放(保留 - 1)只有一次(第二设置器实际上释放的第一个对象,但只有一个时间要么)。所以两者都会永远留在记忆中。

无泄漏:

svc.2results = [[self.results1 mutableCopy] autorelease]; 
^retain +1     ^^^^^^^^^ +1 ^^^^^^^^^^^ -1 later  = retain + 1 

,你会释放(保留 - 1)svc,对象不再保留,它会被释放。

+0

好的,所以我做了result2 NSDictionary和复制,和svc.results2 = [self.results1 autorelease] ...但我需要使它autorelease在第二viewDidUnload时我有[results2发布]?为什么是方法1和2泄漏内存 – 2011-04-10 14:04:42

+0

'svc.results2 = [self.results1 autorelease]'是错误的。完全错误。只有在增加保留数时才需要自动释放它(如果使用副本,则为I.E.)。内存泄漏是因为setter('svc.results2 ='调用setter)正在保留/复制对象本身。 – 2011-04-10 14:29:21