0

Hello
I want to copy elements of one array on another array which is in other class.
For that I have tried various ways like

Both arrays are not in same class.
For eg secondArray is in first.h file and array in in second.h file then when I have made the object of second.h class like this

second *sec; //(in first.h)

and synthesize it
and then I tried to copy array like this sec=[[Second alloc]init];
sec.array=secondarray;
but when i am accessing array in second class it is showing array is null

Does anyone have any idea about this? or any sample code?

2 Answers 2

1

Try doing something along these lines, I have not seen your code so this is probably not an exact solution to your problem, but hopefully it will help you understand the message passing required to solve your problem.

//FirstClass .h file
#import @"SecondClass.h"
@interface FirstClass : NSObject {
    NSArray         *firstArray; 
    SecondClass     *sec; 
}
@property(nonatomic, retain) NSArray        *firstArray; 
@property(nonatomic, retain) SecondClass    *sec; 
@end

//Add this to FistClass .m file
@synthesize firstArray, sec; 

-(id)init{
    if(self == [super init]){
        sec = [[SecondClass alloc] init];
        firstArray = [[NSArray alloc] initWithArray:sec.secondArray];
    }
    return self; 
}

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

//SecondClass .h file
@interface SecondClass : NSObject {
    NSMutableArray          *secondArray;  
}
@property(nonatomic, retain) NSMutableArray     *secondArray; 
@end

//Add this to SecondClass .m file
@synthesize secondArray; 

-(id)init{
    if(self == [super init]){
        secondArray = [[NSMutableArray alloc] initWithObjects:@"Obj1", @"Obj2", @"Obj3", nil];//etc... 
        //Maybe add some more objects (this could be in another method?)
        [secondArray addObject:@"AnotherObj"];

    }
    return self; 
}

-(void)dealloc{
    [secondArray release];
    [super dealloc];
}
Sign up to request clarification or add additional context in comments.

2 Comments

is it necessary to write this code in init method?because i already have objects in secondarray which is coming from xml parsing
No, as long as secondArray inside SecondClass is being contructed before this line is executed inside firstClass: firstArray = [[NSArray alloc] initWithArray:sec.secondArray]; If you fail to do this then secondArray will have a nil value, and will contain no objects to copy into firstArray.
0

Just shouting out a suggestion from my head, but try sec.array = secondarray.

1 Comment

You might want to consider removing your comment, if your marking this post as the solution to your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.