Friday, May 31, 2013

NSArray initWithArray copyItems example in Objective C (iOS).


NSArray initWithArray copyItems

Initializes a newly allocated array using anArray as the source of data objects for the array.

- (id)initWithArray:(NSArray *)array copyItems:(BOOL)flag

Parameters
array
An array containing the objects with which to initialize the new array.
flag
If YES, each object in array receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned array.
If NO, then in a managed memory environment each object in array simply receives a retain message when it is added to the returned array.

Return Value of [NSArray initWithArray copyItems]
An array initialized to contain the objects—or if flag is YES, copies of the objects—in array. The returned object might be different than the original receiver.

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

The copyWithZone: method performs a shallow copy. If you have a collection of arbitrary depth, passing YES for the flag parameter will perform an immutable copy of the first level below the surface. If you pass NO the mutability of the first level is unaffected. In either case, the mutability of all deeper levels is unaffected.

NSArray initWithArray copyItems example.
NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];
[newArray makeObjectsPerformSelector:@selector(doSomethingToObject:)];

Example of [NSArray initWithArray copyItems].
NSArray *_newArray = [[NSArray alloc] initWithArray:_oldArray copyItems:true];

NSArray initWithArray copyItems example.
NSArray *newLists = [[NSArray alloc] initWithArray:[[ListStore sharedStore] lists] copyItems:true];
From the NSArray docs:

- (id)initWithArray:(NSArray *)array copyItems:(BOOL)flag
flag:
If YES, each object in array receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned array.

End of NSArray initWithArray copyItems example article.