objective C: use NSMutableArray in different class

2019-08-29 03:41发布

问题:

I created two UIImageView *image1 and *image2, after I created a NSMutableArray *arrayImage, now I want fill this array

arrayImage = [[NSMutableArray alloc] initWithObjects: image1, image2, nil];

but I created UIImageView and NSMutableArray in a ClassA but I want fill the NSMutableArray in the viewdidload in .m of ClassB, then Xcode tell me that image1 and image2 are undeclared. I just used property and synthesize. What can I do?

回答1:

You can try something like this, you have to keep a reference to classB inside classA so that when you want to add a view to array in classB you can access classB's properties through classA's clasB property. Try something like this.

//ClassA .h file 
#import @"ClassB.h"
@interface ClassA : UIViewController { 
    UIImageView     *view1, view2*;
    ClassB          *classB; 
}
@end

//Inside ClassA .m file 
-(void)viewDidLoad{
    //construct view1 and view2 here or make the IBOutlets and link them in IB 
    classB = [[ClassB alloc] init];
    [classB.imageArray addObject:view1];
    [classB.imageArray addObject:view2];
}

//ClassB .h file 
@interface ClassB : UIViewController {
    NSMutableArray *imageArray; 
}
@property(nonatomic, retain) NSMutableArray *imageArray; 
@end


//Inside ClassB .m file
@synthesize imageArray; 

-(id)init{
    if (self = [super init]){
        imageArray = [[NSMutableArray alloc] init];
    }
    return self; 
}

-(void)dealloc{
    [imageArray release];
    [super dealloc];
}


回答2:

use delegation pattern and pass your class a object to class b like

if your class b

id a;

@property (nonatomic, assign) id a;

and synthesize it.

now init your class b in class a then ,

b.a=self;

thats it now your can use in viewdidload in class b as

self.a.arrayImage 

and study delegate pattern in internet , you will have clear view. good luck