2013-04-22 26 views
0

我收到錯誤「未聲明的標識符」的註釋行:爲什麼同一個類中定義的函數會被視爲未聲明?如何正確申報?

- (BOOL) isInIntArray:(NSInteger[])array theElem:(int)elem{ 
    int i = 0; 
    NSInteger sizeOfArray = (sizeof array)/(sizeof array[0]); 
    while(i < sizeOfArray){ 
     if(array[i] == elem){ 
      return TRUE; 
     } 
     i++; 
    } 
    return FALSE; 
} 

- (int)getNextUnusedID{ 
    int i = rand()%34; 
    while ([isInIntArray:idsUsed theElem:i]) { //here: Use of undeclared identifier 'isInIntArray' 
     i = rand()%34; 
    } 
    return i; 
} 

我真的不明白爲什麼,他們是在同一個.m文件。 爲什麼會這樣?

此外,此代碼:

NSInteger sizeOfArray = (sizeof array)/(sizeof array[0]); 

是給我的警告:

的sizeof對數組函數將返回的sizeof 'NSInteger的*'(又名: '詮釋*'),而不是「 NSInteger的[]'」

我應該如何正確地確定數組的大小?

+0

整個方法是錯誤的。它不以這種方式工作。我想你來自一些腳本語言或C++。你應該使用對象('NSArray'和'NSNumber')。 – Tricertops 2013-04-22 12:32:46

+0

第二個問題:警告應該不言自明:您的變量數組不是數組,而是一個指向數組的指針,因此sizeof將爲您提供指針的大小。 – 2013-04-22 12:39:52

回答

2

正如@CaptainRedmuff指出的那樣,您在方法調用中缺少目標對象,即self

//[object methodParam:x param:y]; 

[self isInIntArray:idsUsed theElem:i]; 

關於你的第二問:在C語言你不能確定數組的大小。這就是爲什麼他們沒有使用,因爲我們有這個對象。我建議你使用這些:

NSMutableArray *array = [[NSMutableArray alloc] init]; // to create array 
array[0] = @42; // to set value at index, `@` creates objects, in this case NSNumber 
[array insertObject:@42 atindex:0]; // equivalent to the above 
NSInteger integer = array[0].integerValue; // get the value, call integerMethod to get plain int 
integer = [[array objectAtIndex:0] integerValue]; // equivalent to the above 
[array containsObject:@42]; // test if given object is in the array 
[array indexOfObject:@42]; // get index of object from array, NSNotFound if not found 
array.count; // to get the number of objects 

重要:這些陣列具有可變大小和它們不限!但是,您只能在索引0 ..(n-1)(其中n的對象數)中訪問元素,並且可以僅爲索引0..n設置值。
換句話說,你不能爲空數組做array[3] = @42;,你需要先填充前3個位置(索引0,1和2)。

6

看起來你已經從該行錯過了self

while ([isInIntArray:idsUsed theElem:i]) 

這應該是:在.h文件中

while ([self isInIntArray:idsUsed theElem:i]) 
+1

CaptainRedmuff是正確的。作爲解釋:isInIntArray:theElem:不是一個函數,而是一個方法,它必須被髮送到它自己定義的對象。 – 2013-04-22 12:37:36

+0

謝謝,我沒有注意到'自我'之間的區別。和'自我'。現在我明白了。 – EBM 2013-04-22 13:18:45

0

寫這個(聲明函數)

- (BOOL) isInIntArray:(NSInteger[])array theElem:(int)elem; 

和使用以下方法調用該方法

while ([self isInIntArray:idsUsed theElem:i]) { //here: Use of undeclared identifier 'isInIntArray' 
      i = rand()%34; 
    } 
相關問題