简体   繁体   中英

NSMutableDictionary initialization in non-ARC app

I don't know if I'm completely brainfarting today, or what. But basically I'm trying to initialize a NSMutableDictionary to be used. I have it as a property:

@property (nonatomic, retain) NSMutableDictionary *baseViewDictionary;

in the .m file:

@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];

I thought this was a pattern to be used to initialize a NSMutableDictionary. Unfortunately, my self.baseViewDictionary never gets set. My tempDict has 1 key/value pair I see in the debugger, but my self.baseViewDictionary has 0x0000000. So it's like

self.baseViewDictionary = tempDict;

never gets run. When I step into that line of code, it jumps to the @synthesize baseViewDictoinary, then returns back to the self.baseViewDictionary=tempDict line.

Here's the picture of the debugger after setObject@"test" gets run.

在此处输入图片说明

Your pattern is correct.
The initialization is done right, no memory leak as you release the dictionary after the assignation to the property, which retains it.

Are your sure your init method is correct?
I mean, calling self = [ super init ] (not == ), doing your stuff after this, and returning self ?

It may seem obvious, but as your instance variable seems to be nil , self may be nil also...

- ( 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM