objective C: use NSMutableArray in different classes

佐手、 提交于 2019-12-12 05:39:43

问题


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



来源:https://stackoverflow.com/questions/5647154/objective-c-use-nsmutablearray-in-different-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!