1

I have two classes. First one downloads data images and adds them to array one after another. When it's done with all 16 of them runs action to switch view to the second one. My problem here is how to access the array from first class in second class?

Here is the code:

first.h

@interface first{
    NSMutableArray *imagesArray;
}
@property(nonatomic,retain)NSMutableArray *imagesArray;

(array is synthetized in .m file)

second.h

#import"second";
#import"first.h"

second.m

-(void) viewdidload {
    first *another = [[another alloc] init];
    label.text =  [NSString stringWithFromat:@"%i",[another.imagesArray count]];
    imageView.image = [another.imagesArray objectAtIndex:0];
}

label shows 0 and imageView shows nothing. Any ideas?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
  • you can create global array or define same `@property(nonatomic,retain)NSMutableArray *imagesArray;` in **second.h** and when you push from First to Second then pass that array. so you don't need to alloc first view. – ChintaN -Maddy- Ramani Sep 02 '14 at 04:19
  • http://stackoverflow.com/questions/6678097/how-to-pass-an-array-from-one-view-controller-to-another and http://stackoverflow.com/questions/15789163/add-objects-to-an-array-from-another-view-controller may help – Dhaval Bhadania Sep 02 '14 at 04:31

2 Answers2

0

Please get a good understanding about Object-Oriented Features & Object Communication in Objective-C

Do not create a new instance of first class. This will create a new first memory object.

You have to access the existing imagesArray class object that created in existing first class.

To do this, declare a NSMutableArray property in your second.m as weak and assign it from first.m class while you allocating second.m.

Example:

@interface second {

    NSMutableArray *parentImagesArray;
}

@property(nonatomic, weak)NSMutableArray *parentImagesArray;

first.m

You will have the similar code in your first.m file

second *secondView = [[second alloc] init];
secondView.parentImagesArray = self.imagesArray; //assign the weak property.

second.m

label.text =  [NSString stringWithFromat:@"%i",[self.parentImagesArray count]];
imageView.image = parentImagesArray objectAtIndex:0];
Shamsudheen TK
  • 30,739
  • 9
  • 69
  • 102
0

there is two way to achieve your goal...

1) FIRST (pass array from first Controller to Second Controller)

make array object in second controller.h then

from first controller where you present second controller

second.array_object = first.array_name;

In this way you got the array in second controller...

2) declare array as globle

Declare array before import statement.
in first.h file

NSMutableArray *arr1;
#import<UIKit/UIKit.h>

now whenever and wherever you want to use this array import .h file in which you declare this array and use it directly without creating any objects...

hope this helps you...

Ashish Ramani
  • 1,214
  • 1
  • 17
  • 30