2013-03-14 113 views
0

我的數組:爲什麼此數組返回0作爲對象計數?

NSMutableArray *squareLocations; 

CGPoint dotOne = CGPointMake(1, 1); 
[squareLocations addObject:[NSValue valueWithCGPoint:dotOne]]; 

CGPoint dotTwo = CGPointMake(10, 10); 
[squareLocations addObject:[NSValue valueWithCGPoint:dotTwo]]; 

CGPoint dotThree = CGPointMake(100, 100); 
[squareLocations addObject:[NSValue valueWithCGPoint:dotThree]]; 

int num = [squareLocations count]; 

for (int i = 0; i < num; i++) 
{ 
    NSValue *pointLocation = [squareLocations objectAtIndex:i]; 
    NSLog(@"%@", pointLocation); 
} 

當我問squareLoctions的對象數,則返回零?但上面要求計數我添加了三個NSValue對象?有人有主意嗎?

回答

7

您需要初始化數組第一

NSMutableArray *squareLocations = [[NSMutableArray alloc] init]; 
+1

+1正確的答案。我只是想我應該添加一個稍微冗長的答案來幫助那個傢伙。 – Till 2013-03-14 02:06:55

+1

超級有選擇性+1,因爲我更喜歡簡短的答案。然後提問者應該研究爲什麼如果他們不明白就是這種情況。 – borrrden 2013-03-14 02:37:38

+0

@borrrden對你的評論大笑:D ......你當然是對的。我只是覺得我應該浪費一分鐘。 – Till 2013-03-14 02:44:35

3

該數組返回0因爲你實際上並不要求其大小的數組。

您假定爲一個數組的對象既沒有被分配,也沒有被正確初始化。

您正在詢問一個當前初始化爲nil的實例。有趣的部分是,它不會崩潰,因爲Objective-C將允許您調用nil實例上的任何方法(選擇器)(呃,該術語不安靜)。只是,那些nil實例將總是返回0NO,0.0f,0.0nil,具體取決於被要求返回值時的預期類型。換句話說,它總是返回一個值,該值在向期望類型轉換時將被設置爲零。


要解決這個問題,你將需要分配,初始化和NSMutableArray的實例分配給您的變量。

這可能或者已經使用了正確的allocinit方法相結合來完成:

NSMutableArray *squareLocations = [[NSMutableArray alloc] init]; 

或者你可以使用的便利性構造例如像之一:

NSMutableArray *squareLocations = [NSMutableArray array]; 

下一次你遇到這種奇怪的行爲,首先檢查相關實例是不是nil

相關問題