2011-04-03 71 views
4

我有一個變量lastPostsGrabbedCounterNSNumber,下面定義。NSNumber不被保留?

.h 
NSNumber *lastPostsGrabbedCounter; 
@property (nonatomic, retain) NSNumber *lastPostsGrabbedCounter; 

.m 
@synthesize postDetailViewController, lastPostsGrabbedCounter; 

- (void)viewWillAppear:(BOOL)animated { 
    self.lastKnownLocation = [[CLLocation alloc] init]; 
    self.lastPostsGrabbedCounter = [[NSNumber alloc] initWithInt:25]; 
[self showActivityViewer]; 

} 

這個.m文件是我主視圖中的表格控制器。當這個應用程序被加載時,這個viewWillAppear被調用,但是如果我導航到另一個TAB並返回並嘗試使用lastPostsGrabbedCounter var,那麼它將顯示爲零?

當我離開時,爲什麼不保留它?

+1

你可以顯示全班的來源嗎?另外,你使用[[NSNumber alloc] initWithInt:25]泄漏了這個數字。你的財產已經保留了這個號碼,所以你應該使用[NSNumber numberWithInt:25]來代替,它是自動發放的並且從財產中獲得一個單獨的保留。 – 2011-04-03 17:26:51

+0

你怎麼知道它不被保留?如果你使用'-retainCount'來檢查,答案就是緩存小的NSNumber,以避免在沒有必要時創建新的對象。你可以在這個其他問題閱讀關於它的一些東西:http://stackoverflow.com/questions/656902/nsnumber-retain-count-issue – 2011-04-03 20:39:00

回答

4

如果NSNumber沒有被保留,那麼你的應用程序會(很可能)崩潰,或者至少表現不好。您看到nil表示發生了非常不同的問題。

檢查以確保您不會在其他代碼路徑上找不到它。另外,確保你回到你認爲你的實例。在整個方法中傳播的極少數NSLog(@"%@ %p", [self class], self]);可以是非常有用的。

André說,你泄漏了這個數字;過度保留它。

+0

每次我離開上面提到的標籤,並返回時,viewWillAppear方法運行,如果我設置即使設置後,斷點我lastPostsGrabbedCounter顯示「無效彙總」? – jdog 2011-04-03 20:18:13

+0

嘗試直接打印對象'po astPostsGrabbedCounter'。這段代碼很簡單,一定有其他的東西壞了。 – bbum 2011-04-03 20:33:40

+0

好吧,試着在上面的評論中添加的所有東西我現在得到「在非線性ABI上不是常量大小的接口'NSNumber'的指針算法 self.lastPostsGrabbedCounter = self.lastPostsGrabbedCounter + 25; 並且線程1:程序接收信號:「EXC_BAD_ACCESS」在這一行 @synthesize postDetailViewController,lastPostsGrabbedCounter; – jdog 2011-04-04 00:49:59