Showing posts with label initWithCapacity example. Show all posts
Showing posts with label initWithCapacity example. Show all posts

Friday, June 21, 2013

NSMutableSet initWithCapacity example in Objective C (iOS).


NSMutableSet initWithCapacity

Returns an initialized mutable set with a given initial capacity.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the set.

Return Value of [NSMutableSet initWithCapacity]
An initialized mutable set with initial capacity to hold numItems members. The returned set might be different than the original receiver.

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

NSMutableSet initWithCapacity example.
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];
or

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

Example of [NSMutableSet initWithCapacity].
NSSet* tom = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* dick = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* harry = [tom setByAddingObjectsFromSet:dick];

printf("tom   retainCount: %d \n", [tom retainCount]);
printf("dick  retainCount: %d \n", [dick retainCount]);
printf("harry retainCount: %d \n", [harry retainCount]);

NSMutableSet initWithCapacity example.
NSMutableSet* collectibleCopy = [[NSMutableSet alloc] initWithCapacity: [_collectibles count]];
for ( id thing in _collectibles ) {
    [collectibleCopy addObject: thing];
}

End of NSMutableSet initWithCapacity example article.

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.

Sunday, June 16, 2013

NSCountedSet initWithCapacity example in Objective C (iOS).


NSCountedSet initWithCapacity

Returns a counted set object initialized with enough memory to hold a given number of objects.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the new counted set.

Return Value
A counted set object initialized with enough memory to hold numItems objects

Discussion of [NSCountedSet initWithCapacity]
The method is the designated initializer for NSCountedSet.

Note that the capacity is simply a hint to help initial memory allocation—the initial count of the object is 0, and the set still grows and shrinks as you add and remove objects. The hint is typically useful if the set will become large.

NSCountedSet initWithCapacity example.
NSDictionary * dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:2], @"bar", nil];
NSDictionary * dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:3], @"bar", nil];
NSDictionary * dict3 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:2], @"foo",
                        [NSNumber numberWithInt:1], @"bar", nil];
NSArray * arrayOfDictionaries = [[NSArray alloc] initWithObjects:
                                 dict1, dict2, dict3, nil];

// count all keys in an array of dictionaries (arrayOfDictionaries):

NSMutableDictionary * countKeys = [[NSMutableDictionary alloc] initWithCapacity:0];
NSCountedSet * counts = [[NSCountedSet alloc] initWithCapacity:0];

NSArray * keys;
NSString * pairString;
NSString * countKey;
for (NSDictionary * dictionary in arrayOfDictionaries)
{
    keys = [dictionary allKeys];
    for (NSString * key in keys)
    {
        pairString = [NSString stringWithFormat:@"%@->%@", key, [dictionary valueForKey:key]];
        if ([countKeys valueForKey:pairString] == nil)
        {
            [countKeys setValue:[NSString stringWithString:pairString] forKey:pairString];
        }
        countKey = [countKeys valueForKey:pairString];
        { [counts addObject:countKey]; }
    }
}

NSLog(@"%@", counts);

[counts release];
[countKeys release];

[arrayOfDictionaries release];
[dict1 release];
[dict2 release];
[dict3 release];

Example of [NSCountedSet initWithCapacity].
UIImage        *image;
int             randomIndex;

NSCountedSet   *set    = [[NSCountedSet alloc] initWithCapacity:50];
NSMutableArray *arrays = [[NSMutableArray alloc] initWithCapacity:5];

for ( int i = 0; i < 5; i++ ) {
    while ( [set count] < 50 ) {
        randomIndex = arc4random() % 6;
        image = [images objectAtIndex:randomIndex];

        switch ( [set count] ) {
            case 48:
            case 49:
                if ( [set countForObject:image] < 9 ) {
                    [set addObject:image];
                }
                break;

            default:
                if ( [set countForObject:image] < 8 ) {
                    [set addObject:image];
                }
        }
    }

    [arrays addObject:[set allObjects]];
    [set removeAllObjects];
}

[set release];

NSCountedSet initWithCapacity example.
@implementation NSString(permutation)
- (BOOL)isPermutation:(NSString*)other
{
    if( [self length] != [other length] ) return NO;
    if( [self isEqualToString:other] )    return YES;
    NSUInteger length = [self length];
    NSCountedSet* set1 = [[[NSCountedSet alloc] initWithCapacity:length] autorelease];
    NSCountedSet* set2 = [[[NSCountedSet alloc] initWithCapacity:length] autorelease];
    for( int i = 0; i < length; i++ ) {
        NSRange range = NSMakeRange(i, 1);
        [set1 addObject:[self substringWithRange:range]];
        [set2 addObject:[self substringWithRange:range]];
    }
    return [set1 isEqualTo:set2];
}
@end

End of NSCountedSet initWithCapacity example article.

Sunday, June 2, 2013

NSMutableString initWithCapacity example in Objective C (iOS).


NSMutableString initWithCapacity

Returns an NSMutableString object initialized with initial storage for a given number of characters,

- (id)initWithCapacity:(NSUInteger)capacity

Parameters
capacity
The number of characters the string is expected to initially contain.

Return Value
An initialized NSMutableString object with initial storage for capacity characters. The returned object might be different than the original receiver.

Discussion of [NSMutableString initWithCapacity]
The number of characters indicated by capacity is simply a hint to increase the efficiency of data storage. The value does not limit the length of the string.

NSMutableString initWithCapacity example.
NSString *name = @"abcdefghi" ;
    int len = [name length];
    NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];

    for(int i=len-1;i>=0;i--)
    {
        [reverseName appendFormat:[NSString stringWithFormat:@"%c",[name characterAtIndex:i]]];

    }

    NSLog(@"%@",reverseName);

Example of [NSMutableString initWithCapacity].
NSMutableString *str1 = [[NSMutableString alloc]initWithCapacity:0];
NSMutableString *str2 = [[NSMutableString alloc]initWithCapacity:0];

for(int pq=1; pq {
    str1 = [NSMutableString stringWithFormat:[documentManager wholeTextForPage:pq]];
    str2 = (NSMutableString *)[str2 stringByAppendingFormat:str1];
    NSLog(@"content of page chumma1:  %@",str1);
}

NSLog(@"cwhole text:  %@",str2);

NSMutableString initWithCapacity example.
str1 = [[NSMutableString alloc] initWithCapacity:0];
for (int pq=1; pq<=temp; pq++)
{
  str1 = [str1 stringByAppendingString:[NSString stringWithString:[documentManager wholeTextForPage:pq]]];
}

End of NSMutableString initWithCapacity example article.

Saturday, June 1, 2013

NSMutableData initWithCapacity example in Objective C (iOS).


NSMutableData initWithCapacity

Returns an initialized NSMutableData object capable of holding the specified number of bytes.

- (id)initWithCapacity:(NSUInteger)capacity

Parameters
capacity
The number of bytes the data object can initially contain.

Return Value
An initialized NSMutableData object capable of holding capacity bytes.

Discussion of [NSMutableData initWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.

If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.

NSMutableData initWithCapacity example.
self.receiveData = [[[NSMutableData alloc] initWithCapacity:0] autorelease];
OR

 NSMutableData * myData =  [[NSMutableData alloc] initWithCapacity:0];
   self.receiveData = myData ;
   [myData release];
    myData  = nil ;

Example of [NSMutableData initWithCapacity].

-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

    if (data==nil) {

        data = [[NSMutableData alloc] initWithCapacity:2048];

    }

    [data appendData:incrementalData];

}

NSMutableData initWithCapacity example.
-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
    [data appendData:incrementalData];
}

End of NSMutableData initWithCapacity example article.

NSMutableArray initWithCapacity example in Objective C (iOS).


NSMutableArray initWithCapacity

Returns an array, initialized with enough memory to initially hold a given number of objects.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the new array.

Return Value
An array initialized with enough memory to hold numItems objects. The returned object might be different than the original receiver.

Discussion of [NSMutableArray initWithCapacity]
Mutable arrays expand as needed; numItems simply establishes the object’s initial capacity.

NSMutableArray initWithCapacity example.
- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self)
    {
        self->myArr = [[NSMutableArray alloc] initWithCapacity:height];
    }
    return self;
}

Example of [NSMutableArray initWithCapacity].
@interface Foo : NSObject {
  NSMutableArray *objects;
}

@end

@implementation Foo

- (id) init {
  if (self = [super init]) {
    objects = [[NSMutableArray alloc] initWithCapacity:10]; // What
you are missing!
  }

  return self;
}

NSMutableArray initWithCapacity example.
i.e. I suggest using this:

[[NSMutableArray alloc] initWithCapacity: 16];

rather than this:

[[NSMutableArray arrayWithCapacity: 16] retain];

Both statements have the same net result but the first one avoids the overhead
of ever adding the object to the autorelease pool.


End of NSMutableArray initWithCapacity example article.