2011-04-14 115 views
0

你好
我想复制另一个数组中的其他类中的一个数组的元素。
为此,我尝试了各种方法,如如何将一个数组复制到另一个不在同一个类中的数组中?

两个数组都不在同一个类中。
对于例如secondArray是在first.h文件和阵列中second.h文件 然后当我已second.h类的对象这样

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

和合成它
然后我试图复制数组像这样 sec = [[Second alloc] init];
sec.array = secondarray;
但当我访问第二类中的数组它显示数组为空

有没有人有这方面的想法?或任何示例代码?

回答

1

尝试沿着这些方向行事,我没有看到您的代码,因此这可能不是您问题的确切解决方案,但希望它能帮助您了解解决问题所需的消息传递。

//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]; 
} 
+0

是否有必要在init方法中编写这段代码?因为我已经有第二数组中的对象来自xml解析 – nehal 2011-04-14 09:44:31

+0

不,只要secondClass中的secondArray在firstClass内执行此行之前被构造:firstArray = [[NSArray alloc] initWithArray:sec.secondArray];如果你没有做到这一点,那么secondArray将有一个零值,并且不会包含任何要复制到firstArray中的对象。 – Sabobin 2011-04-14 09:47:20

0

只是从我脑袋里喊出一个建议,但试试sec.array = secondarray

+0

如果您将此帖标记为问题的解决方案,您可能需要考虑删除您的评论。 – Sabobin 2011-04-14 09:59:45

相关问题