2011-03-30 83 views
0

如何访问已在不同类中水化的NSMutableArray? 有我的示例代码:在不同对象中访问NSMutableArray

Class1.h:我有一个iVar NSMutableArray *anArray; 我@synthesize anArray;Class1.m

在RootViewController的我导入Class1.h和接口ADDD @Class "Class1"; 的我在RootViewController.m@synthesize它添加Class1 *aClass1;并在ViewWillAppear

aClass1 = [[Class1 alloc] init]; 
aClass1.anArray = [[NSMutableArray alloc] initWithObjects: @"string1",@"string2",nil]; 
NSLog(@"aClass1.anArray is Class1 %@",aClass1.anArray); // It works as I expected 

现在在新类我称之为DetailsViewController 与RootViewController.h相同,我导入了.h和@class "Class1";。 另外在DetailsViewController.m我已经导入了"Class1.h"

所以现在在DetailsViewController我尝试做这在viewWillAppear中

NSLog(@"aClass1.anArray in DetailsViewController %@",aClass1.anArray); // PROBLEM: It comes back as null 

我在这个地址加入此示例项目:http://www.epicdesign.com.au/test2.zip

回答

0

你'请访问您尚未在Class1.h中声明的属性,因此您必须在其中添加:

@property (nonatomic, copy) NSMutableArray *anArray; 

既然它应该工作,我宁愿不传递任何NSMutableArray作为参数。你最好在Class1.h中声明一个NSArray属性,将它传递给你的方法,然后在mutableCopy之上你想对数组做修改(只在方法中)。请记住,mutableCopy和copy会增加数组的保留数量,因此您必须在完成后释放它。

1

在您将其推到导航控制器上之前,您只是忘了设置详细信息视图控制器的aClass1 ivar。下面是代码,应该在您的didSelectRowAtIndexPath方法方法:

DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil]; 
// ... 
// Pass the selected object to the new view controller. 
detailViewController.aClass1 = aClass1; // this line was added 
[self.navigationController pushViewController:detailViewController animated:YES]; 
[detailViewController release]; 

一旦你补充一点,我在上面添加的线,你的阵列现在将正确的详细视图控制器显示。