2012-01-25 52 views
1

我創建了兩個可變數組 - referenceArray & stemArray,然後用URL填充referenceArray。我想使stemArray成爲referenceArray的精確副本。我收集,使 賦值stemArray = referenceArray;是不正確的(奇怪的事情發生在我嘗試這個時)。必須有更好的方法,然後簡單地創建第二個循環&這樣填滿stemArray?我仍然不太滿意指針&我相信這種情況是潛在的雷區......任何提示或建議?在此先感謝:)製作數組副本

referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems]; 
    referenceArray = [[NSMutableArray alloc] init]; 

    stemArray = [NSMutableArray arrayWithCapacity:numberOfStems]; 
    stemArray = [[NSMutableArray alloc] init]; 

for (int i = 1; i <= numStems; i++) { 
    NSString *soundName = [NSString stringWithFormat:@"stem-%i", i]; 
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"]; 
    NSURL *soundFile = [[NSURL alloc] initFileURLWithPath:soundPath]; 
    [referenceArray addObject:soundFile]; 
} 

回答

3

你之後,你創建它們覆蓋指向你的可變陣列 - 爲什麼這些alloc/init線在那裏?如果你想要一個NSArray的副本,只需發送一個copy消息:

referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems]; 

for (int i = 1; i <= numStems; i++) { 
    // Fill in referenceArray 
} 

stemArray = [referenceArray copy]; 
+0

我的程序不會不分配/初始化線正常運行(eventhough這是技術上的錯誤是在這種情況下工作) - 我需要的是 ReferenceArr ay = [[NSMutableArray alloc] initWithCapacity:numberOfStems]; 感謝您的幫助,「複製」信息正是我一直在尋找的。 – Octave1

2

你爲什麼不能只是ALLOC &初始化stemArray您填充referenceArray後?

做這樣的事情:

stemArray = [[NSMutableArray alloc] initWithArray: referenceArray];

而且,擺脫了雙頁頭的你在那裏做什麼(即arrayWithCapacity線)。

1

這裏有幾個問題。讓我們通過現有的代碼一步一步:

// You are making a new mutable array that has a starting capacity of numberOfStems and assigning it to the referenceArray variable 
referenceArray = [NSMutableArray arrayWithCapacity:numberOfStems]; 

// You then create another new mutable array with the default capacity and re-assign the referenceArray variable. Fortunately, the first array was created with -arrayWithCapacity: instead of -init...; thus, you aren't leaking an object 
referenceArray = [[NSMutableArray alloc] init]; 

// Same as above 
stemArray = [NSMutableArray arrayWithCapacity:numberOfStems]; 
stemArray = [[NSMutableArray alloc] init]; 

for (int i = 1; i <= numStems; i++) { 
    // This part looks fine 
    NSString *soundName = [NSString stringWithFormat:@"stem-%i", i]; 
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"]; 
    NSURL *soundFile = [[NSURL alloc] initFileURLWithPath:soundPath]; 
    [referenceArray addObject:soundFile]; 

    // If you are in ARC, you are fine. If non-ARC, you are leaking soundFile and need to do: 
    // [soundFile release]; 
} 

根據您的原始描述,你可能希望通過stemArray聲明移動到結束,並使用-copy或-mutableCopy:

stemArray = [referenceArray mutableCopy]; // If stemArray is defined as an NSMutableArray 

或:

stemArray = [referenceArray copy]; // If stemArray is defined as an NSArray