Friday, May 31, 2013

NSArray arrayWithObjects example in Objective C (iOS).

NSArray arrayWithObjects

Creates and returns an array containing the objects in the argument list.

+ (id)arrayWithObjects:(id)firstObj, ...

firstObj, ...
A comma-separated list of objects ending with nil.

Return Value
An array containing the objects in the argument list.

Discussion of [NSArray arrayWithObjects]
This code example creates an array containing three different types of element:

NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = @"a string";

myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];

NSArray arrayWithObjects example.
NSString *strings[3];
strings[0] = @"foo";
strings[1] = @"bar";
NSArray *array = [NSArray arrayWithObjects:strings count:2];

Example of [NSArray arrayWithObjects].
  NSMutableArray * array = [NSMutableArray arrayWithObjects:
                            [NSDictionary dictionaryWithObject:@"1" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"2" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"3" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"4" forKey:@"my_label"],
                            [NSDictionary dictionaryWithObject:@"5" forKey:@"my_label"],
  NSSortDescriptor * sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"my_label" ascending:YES] autorelease];
  [array sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

NSArray arrayWithObjects example.
    NSMutableArray *arrayToFilter = [[NSMutableArray arrayWithObjects:@"Photoshop", @"Flex", @"AIR",@"Flash", @"Acrobat", nil] autorelease];

NSMutableArray *productsToRemove = [[NSMutableArray array] autorelease];
for (NSString *products in arrayToFilter) {
    if (fliterText && [products rangeOfString:fliterText options:NSLiteralSearch|NSCaseInsensitiveSearch].length == 0)
        [productsToRemove addObject:products];
[arrayToFilter removeObjectsInArray:productsToRemove];

End of NSArray arrayWithObjects example article.