2012-05-23 28 views
1

我不知道我今天是否完全腦筋急轉彎,或者是什麼。但基本上我試圖初始化一個NSMutableDictionary使用。我把它作爲一個屬性:在非ARC應用程序中初始化NSMutableDictionary

@property (nonatomic, retain) NSMutableDictionary *baseViewDictionary; 
在.m文件

@synthesize baseViewDictionary; 



// in the init method: 
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithCapacity:0]; 
    self.baseViewDictionary = tempDict; 
    [self.baseViewDictionary setObject:@"test" forKey:[NSNumber numberWithInteger:0]]; 
    [tempDict release]; 

我認爲這是要用來初始化的NSMutableDictionary的模式。不幸的是,我的self.baseViewDictionary永遠不會被設置。我的tempDict有1個鍵/值對,我在調試器中看到,但我的self.baseViewDictionary有0x0000000。所以它就像

self.baseViewDictionary = tempDict; 

永遠不會運行。當我進入該行代碼時,它跳轉到@synthesize baseViewDictoinary,然後返回到self.baseViewDictionary=tempDict行。

下面是運行[email protected]"test"後調試器的圖片。

enter image description here

回答

0

您的模式是正確的。
初始化是正確的,沒有內存泄漏,因爲在分配給屬性後釋放字典,該屬性保留它。

您確定您的init方法正確嗎?
我的意思是,打電話self = [ super init ](不是==),在此之後做你的東西,並返回self

它可能看起來很明顯,但是你的實例變量似乎是nilself可能nil也...

- (id)init 
{ 
    if((self = [ super init ])) 
    { 
     NSMutableDictionary * tempDict = [ [ NSMutableDictionary alloc ] initWithCapacity: 0 ]; 
     self.baseViewDictionary  = tempDict; 

     [ self.baseViewDictionary setObject: @"test" forKey: [ NSNumber numberWithInteger: 0 ] ]; 
     [ tempDict release ]; 

     NSLog(@"%@", self.baseViewDictionary); 
    } 

    return self; 
}