Tutorial by Examples

Creating immutable arrays: NSArray *myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; // Using the array literal syntax: NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"]; ...
NSArray *myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; NSLog (@"Number of elements in array = %lu", [myColors count]);
NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"]; // Preceding is the preferred equivalent to [NSArray arrayWithObjects:...] Getting a single item The objectAtIndex: method provides a single object. The first object in an NSArray is index 0. Si...
NSArray *array = [NSArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", nil]; NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'a'"]; NSArray *beginWithA = [array filteredArrayUsingPredicate:bPredicate]; ...
NSArray *myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; // Convert myColors to mutable NSMutableArray *myColorsMutable = [myColors mutableCopy];
Compare method Either you implement a compare-method for your object: - (NSComparisonResult)compare:(Person *)otherObject { return [self.birthDate compare:otherObject.birthDate]; } NSArray *sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)]; NSSortDescriptor NSS...
NSSet *set = [NSSet set]; NSArray *array = [NSArray array]; NSArray *fromSet = [set allObjects]; NSSet *fromArray = [NSSet setWithArray:array];
NSArray *reversedArray = [myArray.reverseObjectEnumerator allObjects];
NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"]; // Fast enumeration // myColors cannot be modified inside the loop for (NSString *color in myColors) { NSLog(@"Element %@", color); } // Using indices for (NSUInteger i = 0; ...
For added safety we can define the type of object that the array contains: NSArray<NSString *> *colors = @[@"Red", @"Green", @"Blue", @"Yellow"]; NSMutableArray<NSString *> *myColors = [NSMutableArray arrayWithArray:colors]; [myColors addObject:...
NSArray *myColors = @[@"Red", @"Green", @"Blue", @"Yellow"]; [myColors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSLog(@"enumerating object %@ at index %lu", obj, idx); }]; By setting the stop parameter to YES you c...
Arrays can be compared for equality with the aptly named isEqualToArray: method, which returns YES when both arrays have the same number of elements and every pair pass an isEqual: comparison. NSArray *germanMakes = @[@"Mercedes-Benz", @"BMW", @"Porsche", ...
NSArray *a = @[@1]; a = [a arrayByAddingObject:@2]; a = [a arrayByAddingObjectsFromArray:@[@3, @4, @5]]; These methods are optimized to recreate the new array very efficiently, usually without having to destroy the original array or even allocate more memory.

Page 1 of 1