2011-07-03 68 views
0

我正在開發一個iPhone應用程序。檢查NSMutableArray內容

我有以下INIT代碼:

shapes = [NSMutableArray arrayWithCapacity:numShapes]; 

在那之後,我要做到以下幾點:

- (CGSize) sizeOfShapeType:(ShapeType)type{ 
    CGSize shapeSize = CGSizeMake(0, 0); 
    if (shapes != nil) { 
     for(Object2D* obj in shapes) 
      if (obj.figure == type) { 
       shapeSize = obj.size; 
       break; 
      } 
    } 
    return (shapeSize); 
} 

但我總是得到EXEC_BAD_ACCESS因爲形狀各種形狀數組爲空。

如何檢查Object2D是否爲空?

我來到這裏的例外:

for(Object2D* obj in shapes) 

回答

5

arrayWithCapacity返回自動釋放的對象,所以你必須保留它,以確保它不會過早釋放:

shapes = [[NSMutableArray alloc] initWithCapacity:numShapes]; 

// .h file 
@property (nonatomic, retain) NSMutableArray *shapes; 
// .m file 
@synthesize shapes; 
// your init method 
self.shapes = [NSMutableArray arrayWithCapacity:numShapes]; 

對於後一種解決方案,您需要爲形狀ivar聲明帶有retain屬性的屬性。

1

你會得到一個EXC_BAD_ACCESS可能是你沒有權利要求分配給shapes變量對象的所有權,而不是與NSMutableArray問題的原因。我假設shapes是一個實例變量。在調用sizeOfShapeType時,存儲在shapes中的對象已被釋放。

所以解決方案是要求所有權。

shapes = [[NSMutableArray arrayWithCapacity:numShapes] retain]; 
// or 
shapes = [[NSMutableArray alloc] initWithCapacity:numShapes]; 
0
shapes = [NSMutableArray arrayWithCapacity:numShapes]; 

你有沒有實際創建並加載Object2D對象數組?上面的數組初始化將使用空間初始化數組,指向對象的指針數量爲numShapes。但陣列仍然是空的。它不會爲您創建任何Object2D對象。

我很抱歉,如果我說明顯而易見。但是,如果這就是你在init代碼中所做的一切,那麼你錯誤地理解了arrayWithCapacity:的含義。