Wednesday, June 19, 2013

NSMutableDictionary initWithCapacity example in Objective C (iOS).


NSMutableDictionary initWithCapacity

Initializes a newly allocated mutable dictionary, allocating enough memory to hold numItems entries.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the initialized dictionary.

Return Value
An initialized mutable dictionary, which might be different than the original receiver.

Discussion of [NSMutableDictionary initWithCapacity]
Mutable dictionaries allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableDictionary initWithCapacity example.
- ( 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;
}

Example of [NSMutableDictionary initWithCapacity].
#import <Foundation/Foundation.h>

// Model.h
@interface Model : NSObject {
    NSMutableDictionary *piers;
}
@property (nonatomic,retain) NSMutableDictionary *piers;

-(void) createModel;

@end

// Model.m
@implementation Model
@synthesize piers;

-(id) init {
    if (self = [super init]) {
        self.piers = [[NSMutableDictionary alloc] initWithCapacity:2];
        [self createModel];
    }
    return self;
}

-(void) createModel {
    [piers setObject:@"happy" forKey:@"foobar"]; 
}
@end

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    Model *model = [[Model alloc] init];

    NSLog(@"Model: %@", [model.piers objectForKey:@"foobar"]);

    [pool drain];
    return 0;
}

NSMutableDictionary initWithCapacity example.
- (id)init
{
    if ((self = [super init]) == nil) { return nil; }

    bar = [[NSMutableArray alloc] initWithCapacity:0];

    return self;
}

- (void)dealloc
{
    [bar release];

    [super dealloc];
}

- (void)YourMethod
{
    NSMutableDictionary *foo = [[NSMutableDictionary alloc] initWithCapacity:0];
    [foo setObject:[NSNull null] forKey:@"yay"];
    [bar addObject:foo];
    [foo release];
}

End of NSMutableDictionary initWithCapacity example article.