Showing posts with label NSArray. Show all posts
Showing posts with label NSArray. Show all posts

Saturday, June 1, 2013

NSArray NSBinarySearchingInsertionIndex example in Objective C (iOS).


NSArray NSBinarySearchingInsertionIndex

NSBinarySearchingOptions
Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.

enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
};
typedef NSUInteger NSBinarySearchingOptions;
Constants
NSBinarySearchingFirstEqual
Specifies that the search should return the first object in the range that is equal to the given object.
NSBinarySearchingLastEqual
Specifies that the search should return the last object in the range that is equal to the given object.
NSBinarySearchingInsertionIndex
Returns the index at which you should insert the object in order to maintain a sorted array.

NSArray NSBinarySearchingInsertionIndex example.
NSMutableArray *array = …;
id newObject = …;
NSComparator comparator = …;

NSUInteger newIndex = [array indexOfObject:newObject
                             inSortedRange:(NSRange){0, [array count]}
                                   options:NSBinarySearchingInsertionIndex
                           usingComparator:comparator];

[array insertObject:newObject atIndex:newIndex];

Example of [NSArray NSBinarySearchingInsertionIndex].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
    inSortedRange:NSMakeRange(0, values.count)
    options: NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
    usingComparator:^(id a, id b) {
        return [a compare:b];
    }];

NSArray NSBinarySearchingInsertionIndex example.
-(void) /*adding*/
{
    int proposedIndex = 0;
    proposedIndex = [array indexOfObject:node
                                inSortedRange:NSMakeRange(0, array.count)
                                      options:NSBinarySearchingInsertionIndex
                              usingComparator:
                      ^ NSComparisonResult(id obj1, id obj2)
                      {
                          if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
                          if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
                          else return NSOrderedSame;
                      }];

    [array insertObject:node atIndex:proposedIndex];
}

End of NSArray NSBinarySearchingInsertionIndex example article.

NSArray NSBinarySearchingLastEqual example in Objective C (iOS).


NSArray NSBinarySearchingLastEqual

NSBinarySearchingOptions
Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.

enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
};
typedef NSUInteger NSBinarySearchingOptions;
Constants
NSBinarySearchingFirstEqual
Specifies that the search should return the first object in the range that is equal to the given object.
NSBinarySearchingLastEqual
Specifies that the search should return the last object in the range that is equal to the given object.
NSBinarySearchingInsertionIndex
Returns the index at which you should insert the object in order to maintain a sorted array.

NSArray NSBinarySearchingLastEqual example.
You can define a block as a global variable to get an effect similar to functions.

NSComparisonResult (^globalBlock)(id,id) = ^(id lhs, id rhs) {
    if([lhs intValue] < [rhs intValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if([lhs intValue] > [rhs intValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    return (NSComparisonResult)NSOrderedSame;
};
Then, in the method doing the comparison:

int index1 = [array indexOfObject:number
                    inSortedRange:NSMakeRange(0, [array count])
                          options: NSBinarySearchingLastEqual
                  usingComparator:globalBlock];
To put the block in a header, for external use:

NSComparisonResult (^globalBlock)(id,id);

Example of [NSArray NSBinarySearchingLastEqual].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
    inSortedRange:NSMakeRange(0, values.count)
    options: NSBinarySearchingLastEqual | NSBinarySearchingInsertionIndex
    usingComparator:^(id a, id b) {
        return [a compare:b];
    }];

NSArray NSBinarySearchingLastEqual example.
-(id) /* Getting */
{
    int location = [array indexOfObject:node
                                    inSortedRange:NSMakeRange(0, array.count)
                                          options: NSBinarySearchingLastEqual
                                  usingComparator:
                          ^ NSComparisonResult(id obj1, id obj2)
                          {
                              if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
                              if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
                              else return NSOrderedSame;
                          }];
    if (location == NSNotFound) return nil;
    return [array objectAtIndex:location];
}

End of NSArray NSBinarySearchingLastEqual example article.

NSArray NSBinarySearchingFirstEqual example in Objective C (iOS).


NSArray NSBinarySearchingFirstEqual

NSBinarySearchingOptions
Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.

enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
};
typedef NSUInteger NSBinarySearchingOptions;
Constants
NSBinarySearchingFirstEqual
Specifies that the search should return the first object in the range that is equal to the given object.
NSBinarySearchingLastEqual
Specifies that the search should return the last object in the range that is equal to the given object.
NSBinarySearchingInsertionIndex
Returns the index at which you should insert the object in order to maintain a sorted array.

NSArray NSBinarySearchingFirstEqual example.
You can define a block as a global variable to get an effect similar to functions.

NSComparisonResult (^globalBlock)(id,id) = ^(id lhs, id rhs) {
    if([lhs intValue] < [rhs intValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if([lhs intValue] > [rhs intValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    return (NSComparisonResult)NSOrderedSame;
};
Then, in the method doing the comparison:

int index1 = [array indexOfObject:number
                    inSortedRange:NSMakeRange(0, [array count])
                          options:NSBinarySearchingFirstEqual
                  usingComparator:globalBlock];
To put the block in a header, for external use:

NSComparisonResult (^globalBlock)(id,id);

Example of [NSArray NSBinarySearchingFirstEqual].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
    inSortedRange:NSMakeRange(0, values.count)
    options:NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
    usingComparator:^(id a, id b) {
        return [a compare:b];
    }];

NSArray NSBinarySearchingFirstEqual example.
-(id) /* Getting */
{
    int location = [array indexOfObject:node
                                    inSortedRange:NSMakeRange(0, array.count)
                                          options:NSBinarySearchingFirstEqual
                                  usingComparator:
                          ^ NSComparisonResult(id obj1, id obj2)
                          {
                              if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
                              if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
                              else return NSOrderedSame;
                          }];
    if (location == NSNotFound) return nil;
    return [array objectAtIndex:location];
}

End of NSArray NSBinarySearchingFirstEqual example article.

NSArray writeToFile atomically example in Objective C (iOS).


NSArray writeToFile atomically

Writes the contents of the array to a file at a given path.

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Parameters of [NSArray writeToFile atomically]
path
The path at which to write the contents of the array.
If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
flag
If YES, the array is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Return Value of [NSArray writeToFile atomically]
YES if the file is written successfully, otherwise NO.

Discussion of [NSArray writeToFile atomically]
If the array’s contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

NSArray writeToFile atomically example.
//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];

//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
{
    //Array file didn't exist... create a new one
    yourArray = [[NSMutableArray alloc] initWithCapacity:10];

    //Fill with default values
}
...
//Use the content
...
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];

Example of [NSArray writeToFile atomically].
if(![array containsObject:dictionary])
{
[array addObject:dictionary];
if(![array writeToFile:path atomically:YES])
{
NSLog(@".plist writing was unsucessfull");
}
     }

NSArray writeToFile atomically example.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *issueURLsPlist = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];

MyClass * myObject = [[MyClass alloc] init];
NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:myObject];
[array writeToFile:issueURLsPlist atomically:YES];

End of NSArray writeToFile atomically example article.

NSArray writeToFile example in Objective C (iOS).


NSArray writeToFile

Writes the contents of the array to a file at a given path.

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Parameters of [NSArray writeToFile]
path
The path at which to write the contents of the array.
If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.
flag
If YES, the array is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the array is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.

Return Value of [NSArray writeToFile]
YES if the file is written successfully, otherwise NO.

Discussion of [NSArray writeToFile]
If the array’s contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects), the file written by this method can be used to initialize a new array with the class method arrayWithContentsOfFile: or the instance method initWithContentsOfFile:. This method recursively validates that all the contained objects are property list objects before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

NSArray writeToFile example.
//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];

//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
{
    //Array file didn't exist... create a new one
    yourArray = [[NSMutableArray alloc] initWithCapacity:10];

    //Fill with default values
}
...
//Use the content
...
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];

Example of [NSArray writeToFile].
if(![array containsObject:dictionary])
{
[array addObject:dictionary];
if(![array writeToFile:path atomically:YES])
{
NSLog(@".plist writing was unsucessfull");
}
     }

NSArray writeToFile example.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *issueURLsPlist = [documentsDirectory stringByAppendingPathComponent:@"test.plist"];

MyClass * myObject = [[MyClass alloc] init];
NSMutableArray * array = [[NSMutableArray alloc] init];
[array addObject:myObject];
[array writeToFile:issueURLsPlist atomically:YES];

End of NSArray writeToFile example article.

NSArray subarrayWithRange example in Objective C (iOS).


NSArray subarrayWithRange

Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range.

- (NSArray *)subarrayWithRange:(NSRange)range

Parameters
range
A range within the receiving array’s range of elements.

Return Value
A new array containing the receiving array’s elements that fall within the limits specified by range.

Discussion of [NSArray subarrayWithRange]
If range isn’t within the receiving array’s range of elements, an NSRangeException is raised.

For example, the following code example creates an array containing the elements found in the first half of wholeArray (assuming wholeArray exists).

NSArray *halfArray;
NSRange theRange;

theRange.location = 0;
theRange.length = [wholeArray count] / 2;

halfArray = [wholeArray subarrayWithRange:theRange];

NSArray subarrayWithRange example.
NSUInteger size = 50;

for (NSUInteger i = 0; i * size < [testArray count]; i++) {
  NSUInteger start = i * size;
  NSRange range = NSMakeRange(start, MIN([testArray count] - start, size));
  [sortedArray addObject:[testArray subarrayWithRange:range]];
}

Example of [NSArray subarrayWithRange].
 static const int kItemsPerView = 20;
 NSRange rangeForView = NSMakeRange( viewIndex * kItemsPerView, kItemsPerView );
 NSArray *itemsForView = [completeArray subarrayWithRange: rangeForView];

NSArray subarrayWithRange example.
NSMutableArray *arrayOfArrays = [NSMutableArray array];

int itemsRemaining = [stuff count];
int j = 0;

while(j < [stuff count]) {
    NSRange range = NSMakeRange(j, MIN(30, itemsRemaining));
    NSArray *subarray = [stuff subarrayWithRange:range];
    [arrayOfArrays addObject:subarray];
    itemsRemaining-=range.length;
    j+=range.length;
}

End of NSArray subarrayWithRange example article.

NSArray sortedArrayWithOptions usingComparator example in Objective C (iOS).


NSArray sortedArrayWithOptions usingComparator

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block.

- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr

Parameters
opts
A bit mask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably).
cmptr
A comparator block.

Return Value of [NSArray sortedArrayWithOptions usingComparator]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.

NSArray sortedArrayWithOptions usingComparator example.
NSArray* sorted = [unsorted sortedArrayWithOptions:0 usingComparator:^(id v1, id v2) {
  float f1 = [v1 floatValue];
  float f2 = [v2 floatValue];

  if (f1 == f2) return NSOrderedSame;
  return (f1 < f2) ? NSOrderedAscending : NSOrderedDescending;
}];

Example of [NSArray sortedArrayWithOptions usingComparator].
NSArray *test = @[@"Å", @"A", @"B"];
NSLocale *swedish = [[NSLocale alloc] initWithLocaleIdentifier:@"sv"];

NSArray *sortedTest = [test sortedArrayWithOptions:0
                                   usingComparator:^(NSString  *v1, NSString *v2) {
    return [v1 compare:v2 options:NSCaseInsensitiveSearch
                 range:NSMakeRange(0, [v1 length])
                locale:swedish];
}];

// Output: A, B, Å

NSArray sortedArrayWithOptions usingComparator example.
- (NSArray *)subDocumentsOrdered
{
if (!subDocumentsOrdered)
{
subDocumentsOrdered = [[[[self subDocument] allObjects] sortedArrayWithOptions:NSSortStable|NSSortConcurrent usingComparator:(NSComparator) ^(SubDocument *stroke1, SubDocument *stroke2)
                          {
                              return [[stroke1 date] compare:[stroke2 date]];
                          }
                          ] mutableCopy];
}
    return subDocumentsOrdered;
}

End of NSArray sortedArrayWithOptions usingComparator example article.

NSArray sortedArrayWithOptions example in Objective C (iOS).


NSArray sortedArrayWithOptions

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block.

- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr

Parameters
opts
A bit mask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably).
cmptr
A comparator block.

Return Value of [NSArray sortedArrayWithOptions]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.

NSArray sortedArrayWithOptions example.
NSArray* sorted = [unsorted sortedArrayWithOptions:0 usingComparator:^(id v1, id v2) {
  float f1 = [v1 floatValue];
  float f2 = [v2 floatValue];

  if (f1 == f2) return NSOrderedSame;
  return (f1 < f2) ? NSOrderedAscending : NSOrderedDescending;
}];

Example of [NSArray sortedArrayWithOptions].
NSArray *test = @[@"Å", @"A", @"B"];
NSLocale *swedish = [[NSLocale alloc] initWithLocaleIdentifier:@"sv"];

NSArray *sortedTest = [test sortedArrayWithOptions:0
                                   usingComparator:^(NSString  *v1, NSString *v2) {
    return [v1 compare:v2 options:NSCaseInsensitiveSearch
                 range:NSMakeRange(0, [v1 length])
                locale:swedish];
}];

// Output: A, B, Å

NSArray sortedArrayWithOptions example.
- (NSArray *)subDocumentsOrdered
{
if (!subDocumentsOrdered)
{
subDocumentsOrdered = [[[[self subDocument] allObjects] sortedArrayWithOptions:NSSortStable|NSSortConcurrent usingComparator:(NSComparator) ^(SubDocument *stroke1, SubDocument *stroke2)
                          {
                              return [[stroke1 date] compare:[stroke2 date]];
                          }
                          ] mutableCopy];
}
    return subDocumentsOrdered;
}

End of NSArray sortedArrayWithOptions example article.

Friday, May 31, 2013

NSArray sortedArrayUsingSelector example in Objective C (iOS).


NSArray sortedArrayUsingSelector

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given selector.

- (NSArray *)sortedArrayUsingSelector:(SEL)comparator

Parameters
comparator
A selector that identifies the method to use to compare two elements at a time. The method should return NSOrderedAscending if the receiving array is smaller than the argument, NSOrderedDescending if the receiving array is larger than the argument, and NSOrderedSame if they are equal.

Return Value of [NSArray sortedArrayUsingSelector]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by the selector comparator.

Discussion of [NSArray sortedArrayUsingSelector]
The new array contains references to the receiving array’s elements, not copies of them.

The comparator message is sent to each object in the array and has as its single argument another object in the array.

For example, an array of NSString objects can be sorted by using the caseInsensitiveCompare: method declared in the NSString class. Assuming anArray exists, a sorted version of the array can be created in this way:

NSArray *sortedArray =
[anArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

NSArray sortedArrayUsingSelector example.
NSArray *sortedValues = [[yourDictionary allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc]init];
for(NSString *valor in sortedValues){
    for(NSString *clave in [yourDictionary allKeys]){
        if ([valor isEqualToString:[yourDictionary valueForKey:clave]]) {
            [orderedDictionary setValue:valor forKey:clave];
        }
    }
}

Example of [NSArray sortedArrayUsingSelector].
NSArray *keys = [dict allKeys];
NSArray *sKeys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSMutableArray *sValues = [[[NSMutableArray alloc] init] autorelease];

for(id k in sKeys) {
    id val = [dict objectForKey:k];
    [sValues addObject:val];
}

NSArray sortedArrayUsingSelector example.
  NSArray *arraysort=[[NSArray alloc] initWithObjects:@"z",@"v",@"a",@"g",@"b", nil];
 NSArray   *sortedArray = [arraysort sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    for (NSString *str in sortedArray) {
        NSLog(@"string %@ ",str);
    }
    NSLog(@"sortedarrayelements %d",[sortedArray count]);

End of NSArray sortedArrayUsingSelector example article.

NSArray sortedArrayUsingFunction context example in Objective C (iOS).


NSArray sortedArrayUsingFunction context

Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

Discussion of [NSArray sortedArrayUsingFunction context]
The new array contains references to the receiving array’s elements, not copies of them.

The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.
[NSArray sortedArrayUsingFunction context]
Given anArray (an array of NSNumber objects) and a comparison function of this type:

NSInteger intSort(id num1, id num2, void *context)
{
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

NSArray sortedArrayUsingFunction context example.
NSArray *sorted_bookings = [myUnsortedArray sortedArrayUsingFunction:Sort_Bookingdate_Comparer context:self];  

NSInteger Sort_Bookingdate_Comparer(id id1, id id2, void *context)
{
    // Sort Function
    Booking* booking1 = (Booking*)id1; 
    Booking* booking2 = (Booking*)id2; 

    return ([booking1.BOOKING_DATE compare:booking2.BOOKING_DATE]);
}

Example of [NSArray sortedArrayUsingFunction context].
NSInteger personSort(id p1, id p2, void *context)
{
    NSString *name1 = [(MYPersonClass *)p1 firstName];
    NSString *name2 = [(MYPersonClass *)p2 firstName];
    return [name1 compare:name2]
}

NSArray *sortedPerson = [allPeople sortedArrayUsingFunction:personSort context:NULL];

NSArray sortedArrayUsingFunction context example.
NSInteger sortNames(id id1, id id2, void *context)
{
    // Sort Function
    NSString* name1 = (NSString*)id1; 
    NSString* name2 = (NSString*)id2; 

    return ([name1 compare:name2]);
}

int main (int argc, const char * argv[])
{
    NSArray *unsorted = [NSArray arrayWithObjects:@"John", @"Bob", @"Avril", nil];
    NSArray *names = [unsorted sortedArrayUsingFunction:sortNames context:nil];  

    for (NSString* item in names)
    {
        NSLog(@"%@", item);
    }

    return 0;
}

End of NSArray sortedArrayUsingFunction context example article.

NSArray sortedArrayUsingFunction example in Objective C (iOS).


NSArray sortedArrayUsingFunction

Returns a new array that lists the receiving array’s elements in ascending order as defined by the comparison function comparator.

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

Discussion of [NSArray sortedArrayUsingFunction]
The new array contains references to the receiving array’s elements, not copies of them.

The comparison function is used to compare two elements at a time and should return NSOrderedAscending if the first element is smaller than the second, NSOrderedDescending if the first element is larger than the second, and NSOrderedSame if the elements are equal. Each time the comparison function is called, it’s passed context as its third argument. This allows the comparison to be based on some outside parameter, such as whether character sorting is case-sensitive or case-insensitive.
[NSArray sortedArrayUsingFunction]
Given anArray (an array of NSNumber objects) and a comparison function of this type:

NSInteger intSort(id num1, id num2, void *context)
{
int v1 = [num1 intValue];
int v2 = [num2 intValue];
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
A sorted version of anArray is created in this way:

NSArray *sortedArray; sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

NSArray sortedArrayUsingFunction example.
NSArray *sorted_bookings = [myUnsortedArray sortedArrayUsingFunction:Sort_Bookingdate_Comparer context:self];  

NSInteger Sort_Bookingdate_Comparer(id id1, id id2, void *context)
{
    // Sort Function
    Booking* booking1 = (Booking*)id1; 
    Booking* booking2 = (Booking*)id2; 

    return ([booking1.BOOKING_DATE compare:booking2.BOOKING_DATE]);
}

Example of [NSArray sortedArrayUsingFunction].
NSInteger personSort(id p1, id p2, void *context)
{
    NSString *name1 = [(MYPersonClass *)p1 firstName];
    NSString *name2 = [(MYPersonClass *)p2 firstName];
    return [name1 compare:name2]
}

NSArray *sortedPerson = [allPeople sortedArrayUsingFunction:personSort context:NULL];

NSArray sortedArrayUsingFunction example.
NSInteger sortNames(id id1, id id2, void *context)
{
    // Sort Function
    NSString* name1 = (NSString*)id1; 
    NSString* name2 = (NSString*)id2; 

    return ([name1 compare:name2]);
}

int main (int argc, const char * argv[])
{
    NSArray *unsorted = [NSArray arrayWithObjects:@"John", @"Bob", @"Avril", nil];
    NSArray *names = [unsorted sortedArrayUsingFunction:sortNames context:nil];  

    for (NSString* item in names)
    {
        NSLog(@"%@", item);
    }

    return 0;
}

End of NSArray sortedArrayUsingFunction example article.

NSArray sortedArrayUsingDescriptors example in Objective C (iOS).


NSArray sortedArrayUsingDescriptors

Returns a copy of the receiving array sorted as specified by a given array of sort descriptors.

- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors

Parameters
sortDescriptors
An array of NSSortDescriptor objects.

Return Value
A copy of the receiving array sorted as specified by sortDescriptors.

Discussion of [NSArray sortedArrayUsingDescriptors]
The first descriptor specifies the primary key path to be used in sorting the receiving array’s contents. Any subsequent descriptors are used to further refine sorting of objects with duplicate values. See NSSortDescriptor for additional information.

NSArray sortedArrayUsingDescriptors example.
NSSortDescriptor * frequencyDescriptor =
    [[[NSSortDescriptor alloc] initWithKey:FREQUENCY
                                 ascending:YES] autorelease];

id obj;
NSEnumerator * enumerator = [array objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

NSArray * descriptors =
    [NSArray arrayWithObjects:frequencyDescriptor, nil];
NSArray * sortedArray =
    [array sortedArrayUsingDescriptors:descriptors];

NSLog(@"\nSorted ...");

enumerator = [sortedArray objectEnumerator];
while ((obj = [enumerator nextObject])) NSLog(@"%@", obj);

Example of [NSArray sortedArrayUsingDescriptors].
NSSortDescriptor *country = [[[NSSortDescriptor alloc] initWithKey:@"country" ascending:YES]autorelease];
NSSortDescriptor *city = [[[NSSortDescriptor alloc] initWithKey:@"city" ascending:YES]autorelease];
NSArray *sorted = [bag sortedArrayUsingDescriptors:[NSArray arrayWithObjects: country, city, nil]];

NSArray sortedArrayUsingDescriptors example.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest"  ascending:YES];
    [stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    recent = [stories copy];

End of NSArray sortedArrayUsingDescriptors example article.

NSArray sortedArrayUsingComparator example in Objective C (iOS).


NSArray sortedArrayUsingComparator

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block.

- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr

Parameters
cmptr
A comparator block.

Return Value of [NSArray sortedArrayUsingComparator]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.

NSArray sortedArrayUsingComparator example.
NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {

 if ([obj1 integerValue] > [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedAscending;
 }

 if ([obj1 integerValue] < [obj2 integerValue]) {
      return (NSComparisonResult)NSOrderedDescending;
 }
 return (NSComparisonResult)NSOrderedSame;
}];

Example of [NSArray sortedArrayUsingComparator].
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];
    return [first compare:second];
}];

NSArray sortedArrayUsingComparator example.
NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {
  if ([obj1 position] > [obj2 position]) {
    return (NSComparisonResult)NSOrderedDescending;
  }
  if ([obj1 position] < [obj2 position]) {
    return (NSComparisonResult)NSOrderedAscending;
  }
  return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];

End of NSArray sortedArrayUsingComparator example article.

NSArray reverseObjectEnumerator example in Objective C (iOS).


NSArray reverseObjectEnumerator

Returns an enumerator object that lets you access each object in the array, in reverse order.

- (NSEnumerator *)reverseObjectEnumerator

Return Value of [NSArray reverseObjectEnumerator]
An enumerator object that lets you access each object in the array, in order, from the element at the highest index down to the element at index 0.

Special Considerations
When you use this method with mutable subclasses of NSArray, you must not modify the array during enumeration.

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on OS X v10.5 and later and iOS 2.0 and later.

NSArray reverseObjectEnumerator example.
@implementation NSArray (Reverse)

- (NSArray *)reversedArray {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
    NSEnumerator *enumerator = [self reverseObjectEnumerator];
    for (id element in enumerator) {
        [array addObject:element];
    }
    return array;
}

@end

Example of [NSArray reverseObjectEnumerator].
NSMutableArray * reverseArray = [NSMutableArray arrayWithCapacity:[myArray count]];

for (id element in [myArray reverseObjectEnumerator]) {
    [reverseArray addObject:element];
}

NSArray reverseObjectEnumerator example.
NSArray *array2=[myArray mutableCopy];

   NSArray* reversed = [[array2 reverseObjectEnumerator] allObjects];

   [myarray removeAllObjects];

myarray =[reversed mutableCopy];

End of NSArray reverseObjectEnumerator example article.

NSArray pathsMatchingExtensions example in Objective C (iOS).


NSArray pathsMatchingExtensions

Returns an array containing all the pathname elements in the receiving array that have filename extensions from a given array.

- (NSArray *)pathsMatchingExtensions:(NSArray *)filterTypes

Parameters
filterTypes
An array of NSString objects containing filename extensions. The extensions should not include the dot (“.”) character.

Return Value of [NSArray pathsMatchingExtensions]
An array containing all the pathname elements in the receiving array that have filename extensions from the filterTypes array.

NSArray pathsMatchingExtensions example.
- (ViewController *) init {
    if (self = [super init]) self.title = @"Text Files";

    // get the list of .txt files
    directoryList = [[[[NSFileManager defaultManager] directoryContentsAtPath:DOCUMENTS_FOLDER]
                      pathsMatchingExtensions:[NSArray arrayWithObjects:@".txt", nil]] retain];
    NSLog(@"%@", directoryList);

    return self;
}

Example of [NSArray pathsMatchingExtensions].
Yes we have direct method for NSArray below helps you

 NSMutableArray *arrayFiles = [[NSMutableArray alloc] initWithObjects:@"a.png", @"a.jpg",  @"a.pdf", @"h.png", @"f.png", nil];
    NSLog(@"pathsMatchingExtensions----%@",[arrayFiles pathsMatchingExtensions:[NSArray arrayWithObjects:@"png", nil]]);

//my output is
"a.png",
"h.png",
"f.png"

NSArray pathsMatchingExtensions example.
-(NSMutableArray*)searchfiles:(NSString*)basePath ofTypes:(NSArray*)fileTypes{
    NSMutableArray *files = [[[NSMutableArray alloc]init] autorelease];
    NSFileManager *defFM = [NSFileManager defaultManager];
    NSError *error = nil;
    NSArray *dirPath = [defFM contentsOfDirectoryAtPath:basePath error:&error];
    for(NSString *path in dirPath){
       BOOL isDir;
       path = [basePath stringByAppendingPathComponent:path];
       if([defFM fileExistsAtPath:path isDirectory:&isDir] && isDir){
          [files addObjectsFromArray:[self searchfiles:path ofType:fileTypes]];
       }
    }

   NSArray *mediaFiles = [dirPath pathsMatchingExtensions:fileTypes];
   for(NSString *fileName in mediaFiles){
      fileName = [basePath stringByAppendingPathComponent:fileName];
      [files addObject:fileName];
   }

   return files;
}

End of NSArray pathsMatchingExtensions example article.

NSArray objectsAtIndexes example in Objective C (iOS).


NSArray objectsAtIndexes

Returns an array containing the objects in the array at the indexes specified by a given index set.

- (NSArray *)objectsAtIndexes:(NSIndexSet *)indexes

Return Value
An array containing the objects in the array at the indexes specified by indexes.

Discussion of [NSArray objectsAtIndexes]
The returned objects are in the ascending order of their indexes in indexes, so that object in returned array with higher index in indexes will follow the object with smaller index in indexes.

Raises an NSRangeException if any location in indexes exceeds the bounds of the array, of if indexes is nil.

NSArray objectsAtIndexes example.
[yourArray objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(3, yourArray.count - 3)]];

Example of [NSArray objectsAtIndexes].
NSIndexSet *indexes = [activeItems indexesOfObjectsPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqualToString:@"1"];
}];
Once you have the indexes, you can get the subset of the original array, containing just the objects you are interested in, using [NSArray objectsAtIndexes:] (reference):

NSArray *subset = [activeItems objectsAtIndexes:indexes];

NSArray objectsAtIndexes example.
One option would be to convert the array of indexes to an NSIndexSet and then use objectsAtIndexes:

NSArray *objects = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G"];
NSArray *indexArray = @[@(0), @(2), @(6)];

NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSNumber *number in indexArray) {
    [indexSet addIndex:[number unsignedIntegerValue]];
}
NSArray *filtered = [objects objectsAtIndexes:indexSet];

End of NSArray objectsAtIndexes example article.

NSArray objectEnumerator example in Objective C (iOS).


NSArray objectEnumerator

Returns an enumerator object that lets you access each object in the array.

- (NSEnumerator *)objectEnumerator

Return Value
An enumerator object that lets you access each object in the array, in order, from the element at the lowest index upwards.

Discussion of [NSArray objectEnumerator]
Returns an enumerator object that lets you access each object in the array, in order, starting with the element at index 0, as in:

NSEnumerator *enumerator = [myArray objectEnumerator];
id anObject;

while (anObject = [enumerator nextObject]) {
/* code to act on each element as it is returned */
}
Special Considerations
When you use this method with mutable subclasses of NSArray, you must not modify the array during enumeration.

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on OS X v10.5 and later and iOS 2.0 and later.

NSArray objectEnumerator example.
NSEnumerator *e = [array objectEnumerator];
id object;
while (object = [e nextObject]) {
  // do something with object
}

Example of [NSArray objectEnumerator].
NSScreen *screen = nil;
@autoreleasepool{
    NSEnumerator *screenEnumerator = [[NSScreen screens] objectEnumerator];
    while ((screen = [screenEnumerator nextObject]) && !NSMouseInRect(aPoint, screen.frame, NO));
    [screen retain];    // Ensure screen sticks around past return; only under MRR
}
return [screen autorelease];

NSArray objectEnumerator example.
NSMutableArray *numberSort =[[NSMutableArray alloc] init];

    while ((key = [enumerator nextObject])) {
     //(NSNumber *)integer = [key integerValue];
     [numberSort  addObject:[NSNumber numberWithInt:[key intValue]]];
     // code that uses the returned key
    }

    NSArray *stringSort = [numberSort sortedArrayUsingSelector:@selector(compare:)];
    enumerator = [stringSort objectEnumerator];
    NSNumber  *intKey;

    NSMutableArray *backToString =[[NSMutableArray alloc] init];

    while ((intKey = [enumerator nextObject])) {
     //(NSNumber *)integer = [key integerValue];
     [backToString  addObject:[intKey stringValue]];
     // code that uses the returned key

End of NSArray objectEnumerator example article.

NSArray objectAtIndexedSubscript example in Objective C (iOS).


NSArray objectAtIndexedSubscript

Returns the object at the specified index.

- (id)objectAtIndexedSubscript:(NSUInteger)idx

Parameters
idx
An index within the bounds of the array.

Return Value
The object located at index.

Discussion of [NSArray objectAtIndexedSubscript]
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

This method is identical to objectAtIndex:.

NSArray objectAtIndexedSubscript example.
if(i<=[array count]){
    if([array objectAtIndexedSubscript:i]!= nil)
    {
    NSLog("Object present");
    }
    else{
    NSLog("Object Not Present")
    }
}

Example of [NSArray objectAtIndexedSubscript].
for (int i = 0; i < 6; i ++) {
    if ([array objectAtIndexedSubscript:i] == [NSNull null]) {
        NSLog(@"object at index %i has no data", i);
    }
}

NSArray objectAtIndexedSubscript example.
NSString *latitudeValue = [subCoordinates objectForKey:@"0"];
NSString *longitudeValue = [subCoordinates objectForKey:@"1"];

But if the JSON decoding worked, subCoordinates would be an NSArray object and you would have to use this code instead:

NSString *latitudeValue = [subCoordinates objectAtIndexedSubscript:0];
NSString *longitudeValue = [subCoordinates objectAtIndexedSubscript:1];

End of NSArray objectAtIndexedSubscript example article.

NSArray objectAtIndex example in Objective C (iOS).


NSArray objectAtIndex

Returns the object located at index.

- (id)objectAtIndex:(NSUInteger)index

Parameters
index
An index within the bounds of the array.

Return Value
The object located at index.

Discussion of [NSArray objectAtIndex]
If index is beyond the end of the array (that is, if index is greater than or equal to the value returned by count), an NSRangeException is raised.

NSArray objectAtIndex example.
if(i<=[array count]){
    if([array objectAtIndex:i]!= nil)
    {
    NSLog("Object present");
    }
    else{
    NSLog("Object Not Present")
    }
}

Example of [NSArray objectAtIndex].
for (int i = 0; i < 6; i ++) {
    if ([array objectAtIndex:i] == [NSNull null]) {
        NSLog(@"object at index %i has no data", i);
    }
}

NSArray objectAtIndex example.
NSString *latitudeValue = [subCoordinates objectForKey:@"0"];
NSString *longitudeValue = [subCoordinates objectForKey:@"1"];

But if the JSON decoding worked, subCoordinates would be an NSArray object and you would have to use this code instead:

NSString *latitudeValue = [subCoordinates objectAtIndex:0];
NSString *longitudeValue = [subCoordinates objectAtIndex:1];

End of NSArray objectAtIndex example article.

NSArray makeObjectsPerformSelector withObject example in Objective C (iOS).


NSArray makeObjectsPerformSelector withObject

Sends the aSelector message to each object in the array, starting with the first object and continuing through the array to the last object.

- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)anObject

Parameters
aSelector
A selector that identifies the message to send to the objects in the array. The method must take a single argument of type id, and must not have the side effect of modifying the receiving array.
anObject
The object to send as the argument to each invocation of the aSelector method.

Discussion of [NSArray makeObjectsPerformSelector withObject]
This method raises an NSInvalidArgumentException if aSelector is NULL.

NSArray makeObjectsPerformSelector withObject example.
for (id delegate in _delegates)
   [delegate modelDidFinishLoad:self];
or even easier, using NSArray's -makeObjectsPerformSelector:…:

[_delegates makeObjectsPerformSelector:@selector(modelDidFinishLoad:)
                            withObject:self];

Example of [NSArray makeObjectsPerformSelector withObject].
@interface UIButton(setEnabledWithObject)
- (void)setEnabledWithNSNumber:(NSNumber *)bNum;
@end

@implementation UIButton(setEnabledWithObject)
- (void)setEnabledWithNSNumber:(NSNumber *)bNum {
    [self setEnabled:[bNum boolValue]];
}
@end
and then you could use

[buttons makeObjectsPerformSelector:@selector(setEnabledWithNSNumber:) withObject:[NSNumber numberWithBool:NO]];
[buttons makeObjectsPerformSelector:@selector(setEnabledWithNSNumber:) withObject:[NSNumber numberWithBool:YES]];

NSArray makeObjectsPerformSelector withObject example.
int main (int argc, char** argv)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    Card* two = [[Card alloc] initValue:2 withSuit:'d'];
    NSLog(@"Current retain count for the '2' Card: %ud", [two retainCount]);

    Card* three = [[Card alloc] initValue:3 withSuit:'h'];
    Card* four = [[Card alloc] initValue:4 withSuit:'c'];
    NSArray* deck = [NSArray arrayWithObjects:two,three,four,nil];

    NSLog(@"Current retain count for the '2' Card after array retains it: %ud", [two retainCount]);

    [two release];
    [three release];
    [four release];

    NSLog(@"Current retain count for the '2' Card after releasing instance: %ud", [two retainCount]);

    [deck makeObjectsPerformSelector:@selector(displayCard)];

    [deck release];
    NSLog(@"Current retain count for the '2' Card after releasing instances within 'deck' array: %ud", [two retainCount]);

    [pool release];

    return 0;
}

End of NSArray makeObjectsPerformSelector withObject example article.