开发者

Accessing a NSMutableArray from another class

开发者 https://www.devze.com 2023-04-08 04:06 出处:网络
I have a NSMutableArray and I need to access it from another class. This is what I have done so far; I declared NSMutableArray *muArr in the .h file, and @property(nonatomic, retain) NSMutableArray

I have a NSMutableArray and I need to access it from another class. This is what I have done so far;

  1. I declared NSMutableArray *muArr in the .h file, and @property(nonatomic, retain) NSMutableArray *muArr.

  2. @synthasize muArr; in the .m file, and finally populated it: 开发者_StackOverflow中文版

    [muArr addObject: @"First"];

  3. Now in SecondView I added the import statement #import "FirstView.h" and wrote: FirstView *frv = [[FirstView alloc]init]; then NSLog(@"%i",[frv.muArr count]);

These lines of code are written in the viewDidLoad method. and when the NSLog was printed I got 0 records instead of 1.

Why is this? what have I done wrong, and can someone show me a sample code/tutorial?


You are populating muArr in didSelectRowAtIndexPath, which doesn't get called until you select a row. By calling init on your FirstView, you create a new FirstView then immediately check the count of muArr. The count is 0, because you haven't selected any rows yet..


You need to create a property(in the same fashion as you create muArr) in SecondView class

Step 1) : Lets say arrOfSecondView and you synthesize it

Step 2) Now you can add your muArr data to arrOfSecondView

   SecondView *secondView = [[SecondView alloc]init];
   secondView .arrOfFirstView = muArr;
   //and i guess you are pushing to secondView controller

Step 3) Check the arrOfFirstView count


Do you allocate the array? Before you add items to it, you have to allocate it with

myArr = [[NSMutableArray alloc] init];

If you don't do that, the [addObject] call will not crash the program, but won't have any effect. And array's count will remain zero forever.

@synthesize, contrary to a popular belief, does not allocate the ivar. It just generates a getter method and, optionally, a setter method in the class.

0

精彩评论

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

关注公众号