Friday, May 31, 2013

NSArray initWithArray example in Objective C (iOS).


NSArray initWithArray

Initializes a newly allocated array by placing in it the objects contained in a given array.

- (id)initWithArray:(NSArray *)anArray

Parameters of [NSArray initWithArray]
anArray
An array.

Return Value
An array initialized to contain the objects in anArray. The returned object might be different than the original receiver.

Discussion of [NSArray initWithArray]
After an immutable array has been initialized in this way, it cannot be modified.

NSArray initWithArray example.
NSMutableArray * arr1 = [[NSMutableArray alloc]initWithObjects:@"1", @"2", nil];
NSMutableArray * arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];
NSString * no = [arr2 objectAtIndex:0];
NSLog(@"%@", no);

Example of [NSArray initWithArray].
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"1",@"2", nil];
NSMutableArray arr2 = [[[NSArray alloc] initWithArray: arr1 copyItems:YES] mutableCopy];

NSArray initWithArray example.

-(void)createButtons {
    for (int i=0; i<8 data-blogger-escaped-br="" data-blogger-escaped-i="" data-blogger-escaped-nbsp="">         for (int j=0; j<8 data-blogger-escaped-br="" data-blogger-escaped-j="" data-blogger-escaped-nbsp="">            
            UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
            but.frame = CGRectMake(i*60, j*60, 60, 60);
          
            [but setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [but setTitle:@\"text\" forState:UIControlStateNormal];
            [self.view addSubview:but];
           
            [but addTarget:self action:@selector(pressLetter:) forControlEvents:UIControlEventTouchUpInside];
           
            [tempTiles insertObject:but atIndex:(i*8)+j];
           
        }
    }
   
    // tiles is declared as an instance variable of class
    tiles = [[NSArray alloc] initWithArray:tempTiles]; // INSTRUMENTS POINTS TO THIS LINE FOR LEAK
   
    [tempTiles release];

}

End of NSArray initWithArray example article.