2012-04-26 25 views
0

我想連續運行函數中創建一個NSMutableArray的,只是一旦如此,它並不能保持初始化值(從而取代了變更值)作爲函數被反覆稱爲初始化它的值。我的問題是,當我嘗試初始化if語句中的值時,數組中的值不會更改,當我期望打印「值爲1」時,它會保持打印「值爲0」爲什麼我的NSMutableArray在Objective-C中的if語句中更改時不會更改它的值?

這是我的相關代碼:

@property (nonatomic, strong) NSMutableArray * shapeMarked; 
@synthesize shapeMarked; 

//locationManager is the function that's continuously called 

-(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
{ 

//event count is an integer that continuously increases by one each time the 
//parent function is called, this if statement is used so that it only happens 
//once 

if(eventcount == 1){ 

    for (int i = 0; i < 5; i++){ 

     BOOL b = YES; 

     [shapeMarked addObject:[NSNumber numberWithBool:b]]; 

     NSLog(@"value is %d", [[shapeMarked objectAtIndex:i] boolValue]); 

    } 

    } 
} 
+2

'eventcount == 1'曾經匹配過嗎?在這種情況下添加一個NSLog。另外,shapeMarked實際上是一個有效的NSArray?添加一個NSLog(@「array:%@」,shapeMarked);' – Till 2012-04-26 20:14:35

+0

當我添加NSLog(@「array ...);它輸出」array:(null)。我知道「事件計數== 1」匹配,因爲NSLog輸出,如果它不匹配我不會得到輸出,因爲在if語句中調用NSLog。 – user671891 2012-04-26 20:22:08

+1

[NSMutableArray addObject not working]可能的重複(http://stackoverflow.com/questions/1827058/nsmutablearray-addobject-not-working) – 2012-04-26 20:36:36

回答

1

Alloc並初始化數組!你是否?

self.shapeMarked = [NSMutableArray array]; 

例如在你的init方法中應該這樣做。沒有它,你的shapeMarked只是零。

+0

有沒有一種方法可以在任何函數之外執行「@property」或「@synthesize」,因爲當我嘗試在「@property」行上執行該操作時,它會給我帶來錯誤。 – user671891 2012-04-26 20:26:58

+3

你需要去閱讀基本的Objective-C指南;瞭解方法和類,指定的初始化程序等....然後答案將是顯而易見的(你將有成功的基礎)。 – bbum 2012-04-26 20:28:47

+0

正如我寫的,嘗試你的init方法。還釋放dealloc中的對象。 Bbum的建議無疑是一個很好的建議。 – Mario 2012-04-26 20:34:31

1

您的陣列顯然不是有效的NSMutableArray實例 - 或換句話說,它只是nil

這是你的代碼的問題。

nil對象上調用選擇器時,返回值始終爲nil(對於對象)或0(對於標量類型)。調用objectAtIndex:將導致返回nil。您期待NSNumber實例,如前所述,這將是nil。現在,您在nil實例上調用boolValue,那麼將返回0,因爲您期待標量數據類型。看到蘋果出色的Objective-C documentation

您很可能已經忘記用有效的NSMutableArray實例初始化shapeMarked

相關問題