2011-04-14 43 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

相關問題