开发者

Accessing NSMutableArray in an object from different object

开发者 https://www.devze.com 2023-02-20 21:30 出处:网络
How can I get access to a NSMutableArray that has been hydrated in different Class? There is my sample code:

How can I get access to a NSMutableArray that has been hydrated in different Class? There is my sample code:

Class1.h : I have an iVar NSMutableArray *anArray; And I @synthesize anArray; it in Class1.m

In the RootViewController I import the Class1.h and addd @Class "Class1"; The in the interface I add the Class1 *aClass1; in the RootViewController.m I @synthesize it and in the 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

Now in the new class I call it DetailsViewController Same as the RootViewController.h I imported the .h and @class "Class1";. Also in the DetailsViewController.m I have imported the "Class1.h"

So now in the DetailsViewController I try to do this in the viewWillAppear

NSLog(@"aClass1.anArray in DetailsViewController %@",aClass1.an开发者_运维技巧Array);  // PROBLEM: It comes back as null

I have added this sample project in this address: http://www.epicdesign.com.au/test2.zip


You just forgot to set the aClass1 ivar of the details view controller before you pushed it onto the navigation controller. Here is the code that should be in your didSelectRowAtIndexPath method:

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];

Once you add the line that I added above, your array will now show up correctly in the detail view controller.


You're accessing a property that you haven't declared yet in the Class1.h, so you must add there:

@property (nonatomic, copy) NSMutableArray *anArray;

Since it should work, I prefer not to pass any NSMutableArray as parameter. You should better declare a NSArray property in Class1.h to pass it to your methods and then mutableCopy it where you want to make modifications to the array (only inside the methods). And remember that mutableCopy and copy increase the retain count of your array, so you must release it when you are done.

0

精彩评论

暂无评论...
验证码 换一张
取 消