Friday, June 21, 2013

NSNetService initWithDomain example in Objective C (iOS).


NSNetService initWithDomain

Returns the receiver, initialized as a network service of a given type and sets the initial host information.

- (id)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name

Parameters of [NSNetService initWithDomain]
domain
The domain for the service. For the local domain, use @"local." not @"".
type
The network service type.
type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.
name
The name of the service to resolve.

Return Value of [NSNetService initWithDomain]
The receiver, initialized as a network service named name of type type in the domain domain.

Discussion of [NSNetService initWithDomain]
This method is the appropriate initializer to use to resolve a service—to publish a service, use initWithDomain:type:name:port:.

If you know the values for domain, type, and name of the service you wish to connect to, you can create an NSNetService object using this initializer and call resolveWithTimeout: on the result.

You cannot use this initializer to publish a service. This initializer passes an invalid port number to the designated initializer, which prevents the service from being registered. Calling publish on an NSNetService object initialized with this method generates a call to your delegate’s netService:didNotPublish: method with an NSNetServicesBadArgumentError error.

NSNetService initWithDomain example.
I'm not sure, but it looks like the request is not actually scheduled in a run loop for some reason. Maybe try something like this to schedule it?

NSNetService *service = [[[NSNetService alloc] initWithDomain:@"local." type:@"_daap._tcp." name:@"My_Mac"] autorelease];
[service setDelegate:self];
[service scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:@"PrivateMyMacServiceMode"];
[service resolveWithTimeout:8.0];
Stupid question, but are you explicitly implementing NSServiceDelegate protocol or just have the methods?

Example of [NSNetService initWithDomain].
conclusion: publish by first obtaining a port and then use something like:

self.netService = [[NSNetService alloc] initWithDomain:@"local" type:@"_xxx._tcp." name:serviceName port:(int) self.port];
open streams with
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
open streams with (you open a connection here)
EchoConnection * connection = [[EchoConnection alloc] initWithInputStream:( NSInputStream *)readStream outputStream:( NSOutputStream *)writeStream];
        [self.connections addObject:connection];
then browse for services and add them

then open streams on the desired services from the one you browsed with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
(and open them with [istream open] and [ostream open])

NSNetService initWithDomain example.
#import "ServerController.h"

@interface ServerController ()

-(void)startService;
-(void)stopService;

@end

@implementation ServerController

-(void)awakeFromNib {   
    [self startService];
}

-(void)startService {
    netService = [[NSNetService alloc] initWithDomain:@"" type:@"_cocoaforsci._tcp."
        name:@"" port:7865];
    netService.delegate = self;
    [netService publish];
}

-(void)stopService {
    [netService stop];
    [netService release];
    netService = nil;
}

-(void)dealloc {
    [self stopService];
    [super dealloc];
}

#pragma mark Net Service Delegate Methods
-(void)netService:(NSNetService *)aNetService didNotPublish:(NSDictionary *)dict {
    NSLog(@"Failed to publish: %@", dict);
}

@end

End of NSNetService initWithDomain example article.

NSNetService initWithDomain type name example in Objective C (iOS).


NSNetService initWithDomain type name

Returns the receiver, initialized as a network service of a given type and sets the initial host information.

- (id)initWithDomain:(NSString *)domain type:(NSString *)type name:(NSString *)name

Parameters of [NSNetService initWithDomain type name]
domain
The domain for the service. For the local domain, use @"local." not @"".
type
The network service type.
type must contain both the service type and transport layer information. To ensure that the mDNS responder searches for services, as opposed to hosts, prefix both the service name and transport layer name with an underscore character (“_”). For example, to search for an HTTP service on TCP, you would use the type string "_http._tcp.". Note that the period character at the end of the string, which indicates that the domain name is an absolute name, is required.
name
The name of the service to resolve.

Return Value of [NSNetService initWithDomain type name]
The receiver, initialized as a network service named name of type type in the domain domain.

Discussion of [NSNetService initWithDomain type name]
This method is the appropriate initializer to use to resolve a service—to publish a service, use initWithDomain:type:name:port:.

If you know the values for domain, type, and name of the service you wish to connect to, you can create an NSNetService object using this initializer and call resolveWithTimeout: on the result.

You cannot use this initializer to publish a service. This initializer passes an invalid port number to the designated initializer, which prevents the service from being registered. Calling publish on an NSNetService object initialized with this method generates a call to your delegate’s netService:didNotPublish: method with an NSNetServicesBadArgumentError error.

NSNetService initWithDomain type name example.
I'm not sure, but it looks like the request is not actually scheduled in a run loop for some reason. Maybe try something like this to schedule it?

NSNetService *service = [[[NSNetService alloc] initWithDomain:@"local." type:@"_daap._tcp." name:@"My_Mac"] autorelease];
[service setDelegate:self];
[service scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:@"PrivateMyMacServiceMode"];
[service resolveWithTimeout:8.0];
Stupid question, but are you explicitly implementing NSServiceDelegate protocol or just have the methods?

Example of [NSNetService initWithDomain type name].
conclusion: publish by first obtaining a port and then use something like:

self.netService = [[NSNetService alloc] initWithDomain:@"local" type:@"_xxx._tcp." name:serviceName port:(int) self.port];
open streams with
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
open streams with (you open a connection here)
EchoConnection * connection = [[EchoConnection alloc] initWithInputStream:( NSInputStream *)readStream outputStream:( NSOutputStream *)writeStream];
        [self.connections addObject:connection];
then browse for services and add them

then open streams on the desired services from the one you browsed with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
(and open them with [istream open] and [ostream open])

NSNetService initWithDomain type name example.
#import "ServerController.h"

@interface ServerController ()

-(void)startService;
-(void)stopService;

@end

@implementation ServerController

-(void)awakeFromNib {   
    [self startService];
}

-(void)startService {
    netService = [[NSNetService alloc] initWithDomain:@"" type:@"_cocoaforsci._tcp."
        name:@"" port:7865];
    netService.delegate = self;
    [netService publish];
}

-(void)stopService {
    [netService stop];
    [netService release];
    netService = nil;
}

-(void)dealloc {
    [self stopService];
    [super dealloc];
}

#pragma mark Net Service Delegate Methods
-(void)netService:(NSNetService *)aNetService didNotPublish:(NSDictionary *)dict {
    NSLog(@"Failed to publish: %@", dict);
}

@end

End of NSNetService initWithDomain type name example article.

NSNetService hostName example in Objective C (iOS).


NSNetService hostName

Returns the host name of the computer providing the service.

- (NSString *)hostName

Return Value of [NSNetService hostName]
The host name of the computer providing the service. Returns nil if a successful resolve has not occurred.

NSNetService hostName example.
I believe that "hows-testing" is the host name of the computer, not the name of the service. Instead, you want to look at the hostName attribute:

- (void)netServiceDidPublish:(NSNetService *)ns
{
   NSLog(@"Bonjour Service Published: http://%@", [ns hostName]);
}
You should probably also examine the port attribute, and include it in the URL, if the port is something other than the default for that protocol (80 for HTTP)

End of NSNetService hostName example article.

NSNetService getInputStream outputStream example in Objective C (iOS).


NSNetService getInputStream outputStream

Retrieves by reference the input and output streams for the receiver and returns a Boolean value that indicates whether they were retrieved successfully.

- (BOOL)getInputStream:(NSInputStream **)inputStream outputStream:(NSOutputStream **)outputStream

Parameters
inputStream
Upon return, the input stream for the receiver.
outputStream
Upon return, the output stream for the receiver.

Return Value
YES if the streams are created successfully, otherwise NO.

Discussion of [NSNetService getInputStream outputStream]
After this method is called, no delegate callbacks are called by the receiver.

NSNetService getInputStream outputStream example.
Don't believe everything apple claims,

There are a lot of problems with setting up streams with the NSNetworkService.

It will work if you do the following:

First obtain a port to publish the network on. DO NOT PICK A PORT YOURSELF.

Then you can use that port for publishing the network.

Get the client streams with:

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
The error a lot of programmers make is publishing a network by picking a port themselves and then opening the streams with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
The streams will not open....

conclusion: publish by first obtaining a port and then use something like:

self.netService = [[NSNetService alloc] initWithDomain:@"local" type:@"_xxx._tcp." name:serviceName port:(int) self.port];
open streams with
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
open streams with (you open a connection here)
EchoConnection * connection = [[EchoConnection alloc] initWithInputStream:( NSInputStream *)readStream outputStream:( NSOutputStream *)writeStream];
        [self.connections addObject:connection];
then browse for services and add them

then open streams on the desired services from the one you browsed with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
(and open them with [istream open] and [ostream open])

Example of [NSNetService getInputStream outputStream].
I have just changed my method as below

NSInputStream  *tempInput  = nil;
NSOutputStream *tempOutput = nil;

// note the following method returns _inStream and _outStream with a retain count that the caller must eventually release
if (![netService getInputStream:&tempInput outputStream:&tempOutput]) {

    NSLog(@"error in get input and output streams");
    return;
}
_inStream  = tempInput;
_outStream = tempOutput;

NSNetService getInputStream outputStream example.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 if (inputStream && outputStream) [self closeStreams];
   
 if (indexPath.row) {
NSNetService * selectedService = [serviceList objectAtIndex:indexPath.row];
if ([selectedService getInputStream:&inputStream outputStream:&outputStream]) [self openStreams];
serverLabel.text = [[serviceList objectAtIndex:indexPath.row] name];
}
 }

End of NSNetService getInputStream outputStream example article.

NSNetService getInputStream example in Objective C (iOS).


NSNetService getInputStream

Retrieves by reference the input and output streams for the receiver and returns a Boolean value that indicates whether they were retrieved successfully.

- (BOOL)getInputStream:(NSInputStream **)inputStream outputStream:(NSOutputStream **)outputStream

Parameters
inputStream
Upon return, the input stream for the receiver.
outputStream
Upon return, the output stream for the receiver.

Return Value
YES if the streams are created successfully, otherwise NO.

Discussion of [NSNetService getInputStream]
After this method is called, no delegate callbacks are called by the receiver.

NSNetService getInputStream example.
Don't believe everything apple claims,

There are a lot of problems with setting up streams with the NSNetworkService.

It will work if you do the following:

First obtain a port to publish the network on. DO NOT PICK A PORT YOURSELF.

Then you can use that port for publishing the network.

Get the client streams with:

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
The error a lot of programmers make is publishing a network by picking a port themselves and then opening the streams with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
The streams will not open....

conclusion: publish by first obtaining a port and then use something like:

self.netService = [[NSNetService alloc] initWithDomain:@"local" type:@"_xxx._tcp." name:serviceName port:(int) self.port];
open streams with
CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream);
open streams with (you open a connection here)
EchoConnection * connection = [[EchoConnection alloc] initWithInputStream:( NSInputStream *)readStream outputStream:( NSOutputStream *)writeStream];
        [self.connections addObject:connection];
then browse for services and add them

then open streams on the desired services from the one you browsed with

[nService qNetworkAdditions_getInputStream:&istream outputStream:&ostream];
(and open them with [istream open] and [ostream open])

Example of [NSNetService getInputStream].
I have just changed my method as below

NSInputStream  *tempInput  = nil;
NSOutputStream *tempOutput = nil;

// note the following method returns _inStream and _outStream with a retain count that the caller must eventually release
if (![netService getInputStream:&tempInput outputStream:&tempOutput]) {

    NSLog(@"error in get input and output streams");
    return;
}
_inStream  = tempInput;
_outStream = tempOutput;

NSNetService getInputStream example.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 if (inputStream && outputStream) [self closeStreams];
   
 if (indexPath.row) {
NSNetService * selectedService = [serviceList objectAtIndex:indexPath.row];
if ([selectedService getInputStream:&inputStream outputStream:&outputStream]) [self openStreams];
serverLabel.text = [[serviceList objectAtIndex:indexPath.row] name];
}
 }

End of NSNetService getInputStream example article.

NSNetService addresses example in Objective C (iOS).


NSNetService addresses

Returns an array containing NSData objects, each of which contains a socket address for the service.

- (NSArray *)addresses

Return Value
An array containing NSData objects, each of which contains a socket address for the service. Each NSData object in the returned array contains an appropriate sockaddr structure that you can use to connect to the socket. The exact type of this structure depends on the service to which you are connecting. If no addresses were resolved for the service, the returned array contains zero elements.

Discussion of [NSNetService addresses]
It is possible for a single service to resolve to more than one address or not resolve to any addresses. A service might resolve to multiple addresses if the computer publishing the service is currently multihoming.

NSNetService addresses example.
for (NSData* data in [server addresses]) {

    char addressBuffer[100];

    struct sockaddr_in* socketAddress = (struct sockaddr_in*) [data bytes];

    int sockFamily = socketAddress->sin_family;

    if (sockFamily == AF_INET || sockFamily == AF_INET6) {

        const char* addressStr = inet_ntop(sockFamily,
                            &(socketAddress->sin_addr), addressBuffer,
                            sizeof(addressBuffer));

        int port = ntohs(socketAddress->sin_port);

        if (addressStr && port)
            NSLog(@"Found service at %s:%d", addressStr, port);

    }

}

Example of [NSNetService addresses].
for (NSData *address in [service addresses]) {
struct sockaddr_in *socketAddress = (struct sockaddr_in *) [address bytes];
            NSLog(@\"Service name: %@ , ip: %s , port %i\", [service name], inet_ntoa(socketAddress->sin_addr), [service port]);
        }

NSNetService addresses example.
@implementation NSNetService (ipv4)

- (NSArray*)ipv4addresses
{
        NSMutableArray * ipv4addresses = [NSMutableArray array];
        NSArray *addresses = [self addresses];
        int aCount = [addresses count];
        char addr[256];
       
        for (int i = 0; i < aCount; i++) {
                struct sockaddr *socketAddress = (struct sockaddr *)[[addresses 
objectAtIndex:i] bytes];
               
                if (socketAddress && socketAddress->sa_family == AF_INET) {
                        if (inet_ntop(AF_INET, &((struct sockaddr_in *)socketAddress)-
 >sin_addr, addr, sizeof(addr))) {
                               
                                uint16_t port = ntohs(((struct sockaddr_in *)socketAddress)-
 >sin_port);
                               
                                [ipv4addresses addObject:[NSString stringWithFormat:@"%s:%d", 
addr, port]];
                        }
                }
        }
       
        return ipv4addresses;
}

@end


End of NSNetService addresses example article.

NSNetService dataFromTXTRecordDictionary example in Objective C (iOS).


NSNetService dataFromTXTRecordDictionary

Returns an NSData object representing a TXT record formed from a given dictionary.

+ (NSData *)dataFromTXTRecordDictionary:(NSDictionary *)txtDictionary

Parameters
txtDictionary
A dictionary containing a TXT record.

Return Value of [NSNetService dataFromTXTRecordDictionary]
An NSData object representing TXT data formed from txtDictionary. Fails an assertion if txtDictionary cannot be represented as an NSData object.
NSNetService dataFromTXTRecordDictionary example.
NSImage *original = [NSImage imageNamed:NSImageNameComputer];
                [original setSize:NSMakeSize(10.0f, 10.0f)];
                NSData *image = [original TIFFRepresentation];
                NSBitmapImageRep *imageRep = [NSBitmapImageRep 
imageRepWithData:image];
                NSData *finalData = [imageRep representationUsingType:NSPNGFileType 
properties:nil];
                NSDictionary *txtRecord = [NSDictionary 
dictionaryWithObject:finalData forKey:@"image"];
                NSData *data = [NSNetService dataFromTXTRecordDictionary:txtRecord];
                if (data)
                        NSLog(@"Data is not nil!");
                [netService setTXTRecordData:data];


Example of [NSNetService dataFromTXTRecordDictionary].
// Open a stream to the server, finding the server via Bonjour.  Then configure
// the stream for async operation.

//here's the tweak.
//original code looked like -
//self.netService = [[[NSNetService alloc] initWithDomain:@"local." type:@"_x-SNSUpload._tcp." name:@"Test"] autorelease];

self.netService = [[[NSNetService alloc] initWithDomain:@"10.212.19.121" type:@"_smb._tcp." name:@"lanmanserver"] autorelease];

assert(self.netService != nil);

NSDictionary *newDict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"domain\\username",@"password",@"C:\\Documents and Settings\\username\\Desktop\\test%20sharing",nil] forKeys:[NSArray arrayWithObjects:@"u",@"p",@"path",nil]];

[self.netService setTXTRecordData:[NSNetService dataFromTXTRecordDictionary:newDict]];

NSNetService dataFromTXTRecordDictionary example.
NSDictionary *txt = [NSDictionary dictionaryWithObjectsAndKeys:
    [@"1" dataUsingEncoding:NSUTF8StringEncoding], @"txtvers",
    [@"131073" dataUsingEncoding:NSUTF8StringEncoding], @"iTSh Version",
    [@"196610" dataUsingEncoding:NSUTF8StringEncoding], @"Version",
    nil];

NSData *txtData = [NSNetService dataFromTXTRecordDictionary:txt];

[bonjourServer setTXTRecordData:txtData];

End of NSNetService dataFromTXTRecordDictionary example article.

NSMutableSet unionSet example in Objective C (iOS).


NSMutableSet unionSet

Adds each object in another given set to the receiving set, if not present.

- (void)unionSet:(NSSet *)otherSet

Parameters of [NSMutableSet unionSet]
otherSet
The set of objects to add to the receiving set.

NSMutableSet unionSet example.
NSArray *symbols = [NSArray arrayWithObjects:@"AAPL",@"GOOG",@"INTC",@"YHOO",nil];

NSArray *fetchedSymbols = [NSArray arrayWithObjects:@"AMD",@"BIDU",@"GOOG",@"GMCR",@"INTC",@"YHOO",nil];

NSMutableSet* localSet = [[NSMutableSet alloc] initWithArray:symbols];
NSMutableSet* serverSet = [[NSMutableSet alloc] initWithArray:fetchedSymbols];

[localSet unionSet:serverSet];

for (id symbol in localSet) {
    NSLog(@"%@",symbol);
}

Example of [NSMutableSet unionSet].
By using NSSet, as others have pointed out. For

NSArray * a = [NSArray arrayWithObjects: ... ];
NSArray * b = [NSArray arratWithObjects: ... ];
NSMutableSet * set = [NSMutableSet setWithArray:a];
[set intersectSet:[NSSet setWithArray:b];
[set unionSet:[NSSet setWithArray:b];

NSMutableSet unionSet example.
NSMutableArray *first=[NSMutableArray arrayWithArray:@[@"1",@"2",@"3",@"4",@"5",@"6"]];
NSMutableArray *second=[NSMutableArray arrayWithArray:@[@"2",@"4",@"6",@"8",@"0",@"12"]];

NSMutableSet *firstSet  = [NSMutableSet setWithArray:first];
NSMutableSet *secondSet = [NSMutableSet setWithArray:second];
[firstSet unionSet:secondSet];
NSArray *uniqueArray    = [firstSet allObjects];

End of NSMutableSet unionSet example article.

NSMutableSet minusSet example in Objective C (iOS).


NSMutableSet minusSet

Removes each object in another given set from the receiving set, if present.

- (void)minusSet:(NSSet *)otherSet

Parameters of [NSMutableSet minusSet]
otherSet
The set of objects to remove from the receiving set.

NSMutableSet minusSet example.
If duplicate items are not significant in the arrays, you can use the minusSet: operation of NSMutableSet:

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul" nil];

NSSet *firstSet = [NSSet setWithArray:firstArray];
NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]];
[secondSet addObjectsFromArray:secondArray];

NSSet *result = [secondSet minusSet:firstSet];

Example of [NSMutableSet minusSet].
NSMutableSet *countriesSet = [NSMutableSet setWithArray:countriesArray];
NSSet *unSet = [NSSet setWithArray:unCountriesArray];
[countriesSet minusSet:unSet];
// countriesSet now contains only those countries who are not part of unSet

NSMutableSet minusSet example.
The your code could be:

NSMutableSet *web = [[NSMutableSet alloc] initWithObjects:@"2",@"3",@"4",nil];
NSMutableSet *disk = [[NSMutableSet alloc] initWithObjects:@"1",@"2",@"3",nil];

NSMutableSet * remArray = [[NSMutableSet setWithSet:disk] minusSet:web];
NSMutableSet * addArray = [[NSMutableSet setWithSet:web] minusSet:disk];
You can also read the Collections Programming Topics guide. Before using an array you have to determine if you want an ordered collection or not.

End of NSMutableSet minusSet example article.

NSMutableSet intersectSet example in Objective C (iOS).


NSMutableSet intersectSet

Removes from the receiving set each object that isn’t a member of another given set.

- (void)intersectSet:(NSSet *)otherSet

Parameters of [NSMutableSet intersectSet]
otherSet
The set with which to perform the intersection.

NSMutableSet intersectSet example.
Use NSMutableSet:

NSMutableSet *intersection = [NSMutableSet setWithArray:array1];
[intersection intersectSet:[NSSet setWithArray:array2]];
[intersection intersectSet:[NSSet setWithArray:array3]];

NSArray *array4 = [intersection allObjects];

Example of [NSMutableSet intersectSet].
If you are using NSSet you have to create a new NSMutableSet, which has the method intersectSet:, which can be used for your purpose:

NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"2", @"4", @"6", @"8", @"10", @"12", @"14", @"18", nil];

NSLog(@"set1: %@", set1);
NSLog(@"set2: %@", set2);
[set1 intersectSet:set2];
NSLog(@"isec: %@", set1);
You can create a NSMutableSet from an NSArray using the addObjectsFromArray: method:

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObjectsFromArray:array];

NSMutableSet intersectSet example.
Something like this?

NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];
This has the benefit of not looking up the objects in the array, while looping through another array, which has N^2 complexity and may take a while if the arrays are large.

Edit: set2 doesn't have to be mutable, might as well use just

NSSet* set2 = [NSSet setWithArray:array2];

End of NSMutableSet intersectSet example article.

NSMutableSet initWithCapacity example in Objective C (iOS).


NSMutableSet initWithCapacity

Returns an initialized mutable set with a given initial capacity.

- (id)initWithCapacity:(NSUInteger)numItems

Parameters
numItems
The initial capacity of the set.

Return Value of [NSMutableSet initWithCapacity]
An initialized mutable set with initial capacity to hold numItems members. The returned set might be different than the original receiver.

Discussion of [NSMutableSet initWithCapacity]
Mutable sets allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableSet initWithCapacity example.
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];
or

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

Example of [NSMutableSet initWithCapacity].
NSSet* tom = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* dick = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* harry = [tom setByAddingObjectsFromSet:dick];

printf("tom   retainCount: %d \n", [tom retainCount]);
printf("dick  retainCount: %d \n", [dick retainCount]);
printf("harry retainCount: %d \n", [harry retainCount]);

NSMutableSet initWithCapacity example.
NSMutableSet* collectibleCopy = [[NSMutableSet alloc] initWithCapacity: [_collectibles count]];
for ( id thing in _collectibles ) {
    [collectibleCopy addObject: thing];
}

End of NSMutableSet initWithCapacity example article.

NSMutableSet filterUsingPredicate example in Objective C (iOS).


NSMutableSet filterUsingPredicate

Evaluates a given predicate against the set’s content and removes from the set those objects for which the predicate returns false.

- (void)filterUsingPredicate:(NSPredicate *)predicate

Parameters
predicate
A predicate.

Discussion of [NSMutableSet filterUsingPredicate]
The following example illustrates the use of this method.

NSMutableSet filterUsingPredicate example.
NSMutableSet *mutableSet =
    [NSMutableSet setWithObjects:@"One", @"Two", @"Three", @"Four", nil];
NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith 'T'"];
[mutableSet filterUsingPredicate:predicate];
// mutableSet contains (Two, Three)

Example of [NSMutableSet filterUsingPredicate].
If the strings inside the array are known to be distinct, you can use sets. NSSet is faster then NSArray on large inputs:

NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];

NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
[matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];

NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
[notmatches  minusSet:matches];

NSMutableSet filterUsingPredicate example.
 - (void)didSaveNotficiation:(NSNotification*)notification
    {
            NSSet *objects = nil;
            NSMutableSet *combinedSet = nil;
            NSPredicate *predicate = nil;

            NSDictionary *userInfo = [notification userInfo];

            objects = [userInfo objectForKey:NSInsertedObjectsKey];
            combinedSet = [NSMutableSet setWithSet:objects];

            objects = [[notification userInfo] objectForKey:NSUpdatedObjectsKey];
            [combinedSet unionSet:objects];

            objects = [[notification userInfo] objectForKey:NSDeletedObjectsKey];
            [combinedSet unionSet:objects];

//THis is slow
            predicate = [NSPredicate predicateWithFormat:@"entity.name == %@ && %K == %@",
                                                         [XXContact entityName], XXContactRelationship.user,self];
            [combinedSet filterUsingPredicate:predicate];

            if ([combinedSet count] == 0) {
                return;
            }

            [self process];

/* This is much faster
            [combinedSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
                if ([obj isKindOfClass:[XXContact class]]) {
                    XXContact* contact = (XXContact*)obj;
                    if (contact.user == self) {
                        [self process];
                        *stop = YES;
                    }
                }
            }];
*/
}

End of NSMutableSet filterUsingPredicate example article.

NSMutableSet addObjectsFromArray example in Objective C (iOS).


NSMutableSet addObjectsFromArray

Adds to the set each object contained in a given array that is not already a member.

- (void)addObjectsFromArray:(NSArray *)array

Parameters of [NSMutableSet addObjectsFromArray]
array
An array of objects to add to the set.

NSMutableSet addObjectsFromArray example.
NSMutableSet *randomCards = [NSMutableSet setWithCapacity:10];

[randomCards addObjectsFromArray:whiteListArray];

while ([randomCards count] < 10) {
    NSNumber *randomNumber = [NSNumber numberWithInt:(arc4random() % [randoms count])];
    [randomCards addObject:[randoms objectAtIndex:[randomNumber intValue]]];
}

Example of [NSMutableSet addObjectsFromArray].
If you are using NSSet you have to create a new NSMutableSet, which has the method intersectSet:, which can be used for your purpose:

NSMutableSet *set1 = [[NSMutableSet alloc] initWithObjects:@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", nil];
NSMutableSet *set2 = [[NSMutableSet alloc] initWithObjects:@"2", @"4", @"6", @"8", @"10", @"12", @"14", @"18", nil];

NSLog(@"set1: %@", set1);
NSLog(@"set2: %@", set2);
[set1 intersectSet:set2];
NSLog(@"isec: %@", set1);
You can create a NSMutableSet from an NSArray using the addObjectsFromArray: method:

NSArray *array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
NSMutableSet *set = [[NSMutableSet alloc] init];
[set addObjectsFromArray:array];

NSMutableSet addObjectsFromArray example.
NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul" nil];

NSSet *firstSet = [NSSet setWithArray:firstArray];
NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]];
[secondSet addObjectsFromArray:secondArray];

NSSet *result = [secondSet minusSet:firstSet];

End of NSMutableSet addObjectsFromArray example article.

NSMutableSet addObject example in Objective C (iOS).


NSMutableSet addObject

Adds a given object to the set, if it is not already a member.

- (void)addObject:(id)object

Parameters of [NSMutableSet addObject]
object
The object to add to the set.

NSMutableSet addObject example.
- (void)applicationDidFinishLaunching:(UIApplication *)application {   
    NSSet *s=[NSSet setWithObject:@"setWithObject"];
    NSMutableSet *m=[NSMutableSet setWithCapacity:1];
    [m addObject:@"Added String"];
    NSMutableSet *n = [[NSMutableSet alloc] initWithCapacity:1];
    [self showSuperClasses:s];
    [self showSuperClasses:m];
    [self showSuperClasses:n];
    [self showSuperClasses:@"Steve"];  
}

- (void) showSuperClasses:(id) anObject{
    Class cl = [anObject class];
    NSString *classDescription = [cl description];
    while ([cl superclass])
    {
        cl = [cl superclass];
        classDescription = [classDescription stringByAppendingFormat:@":%@", [cl description]];
    }
    NSLog(@"%@ classes=%@",[anObject class], classDescription);
}

Example of [NSMutableSet addObject].
At some point before you use the set, you need to create a new NSMutableSet.

To make it easy, you can use something like the following to automatically allocate a new mutable set when you ask to use it for the first time.

- (NSMutableSet *)NHPList {
    if (NHPList == nil) {
        NHPList = [[NSMutableSet alloc] init];
    }
    return NHPList;
}
You would also have to release the memory, usually in your viewDidUnload method by setting NHPList to nil.

If this is the only place that you set the data, you could also just change this line:

[NHPList addObject:[sub name]];
to:

if (self.NHPList == nil) {
    self.NHPList = [[NSMutableSet alloc] init];
}
[self.NHPList addObject:[sub name]];

NSMutableSet addObject example.
+ (NSSet *)variablesInExpression:(id)anExpression
{
NSMutableSet *setOfVariables = [[NSMutableSet alloc] init];
for (NSString *str in anExpression) {
    if ([str hasPrefix:VARIABLE_PREFIX]) {
        [setOfVariables addObject:str];
    }
}
[setOfVariables autorelease];
return setOfVariables;
}

End of NSMutableSet addObject example article.

NSMutableSet setWithCapacity example in Objective C (iOS).


NSMutableSet setWithCapacity

Creates and returns a mutable set with a given initial capacity.

+ (id)setWithCapacity:(NSUInteger)numItems

Parameters of [NSMutableSet setWithCapacity]
numItems
The initial capacity of the new set.

Return Value
A mutable set with initial capacity to hold numItems members.

Discussion of [NSMutableSet setWithCapacity]
Mutable sets allocate additional memory as needed, so numItems simply establishes the object’s initial capacity.

NSMutableSet setWithCapacity example.
-(NSString *) randomizeHint:(NSString *) wordToShuffle{

    NSString * outputstring = @"";

    NSMutableSet * usedNumberSet = [NSMutableSet setWithCapacity:[wordToShuffle length]];

    for (int i=0; i<[wordToShuffle length]; i++) {
        int randomnum = arc4random()%[wordToShuffle length];

        while ([usedNumberSet containsObject:[NSNumber numberWithInt:randomnum]]==YES) {
            randomnum = arc4random()%[wordToShuffle length];
        }

        [usedNumberSet addObject:[NSNumber numberWithInt:randomnum]];

        // just set outputstring like so... no need to worry about a leaky mutable string then
        outputstring = [outputstring stringByAppendingFormat:@"%c",
                    [wordToShuffle characterAtIndex:randomnum]];
    }

    return outputstring;

}

Example of [NSMutableSet setWithCapacity].
You probably want

NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];
or

NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];

NSMutableSet setWithCapacity example.
NSMutableSet *randomCards = [NSMutableSet setWithCapacity:10];

[randomCards addObjectsFromArray:whiteListArray];

while ([randomCards count] < 10) {
    NSNumber *randomNumber = [NSNumber numberWithInt:(arc4random() % [randoms count])];
    [randomCards addObject:[randoms objectAtIndex:[randomNumber intValue]]];
}

End of NSMutableSet setWithCapacity example article.

NSMutableIndexSet shiftIndexesStartingAtIndex by example in Objective C (iOS).


NSMutableIndexSet shiftIndexesStartingAtIndex by

Shifts a group of indexes to the left or the right within the receiver.

- (void)shiftIndexesStartingAtIndex:(NSUInteger)startIndex by:(NSInteger)delta

Parameters of [NSMutableIndexSet shiftIndexesStartingAtIndex by]
startIndex
Head of the group of indexes to shift.
delta
Amount and direction of the shift. Positive integers shift the indexes to the right. Negative integers shift the indexes to the left.

Discussion of [NSMutableIndexSet shiftIndexesStartingAtIndex by]
The group of indexes shifted is made up by startIndex and the indexes that follow it in the set.

A left shift deletes the indexes in a range the length of delta preceding startIndex from the set.

A right shift inserts empty space in the range (startIndex,delta) in the receiver.

NSMutableIndexSet shiftIndexesStartingAtIndex by example.
- (void) rotateRowRightAtIndex:(NSUInteger)index
{
    NSIndexSet *indexes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(index*4, 4)];
    NSMutableArray *row = [[_values objectsAtIndexes:indexes] mutableCopy];
    [self rotateArrayRight:row];
    [_values replaceObjectsAtIndexes:indexes withObjects:row];
}

- (void) rotateColumnRightAtIndex:(NSUInteger)index
{
    NSMutableIndexSet *indexes = [_indexes0 mutableCopy];
    [indexes shiftIndexesStartingAtIndex:0 by:index];
    NSMutableArray *col = [[_values objectsAtIndexes:indexes] mutableCopy];
    [self rotateArrayRight:col];
    [_values replaceObjectsAtIndexes:indexes withObjects:col];
}

End of NSMutableIndexSet shiftIndexesStartingAtIndex by example article.

NSMutableIndexSet removeIndexesInRange example in Objective C (iOS).


NSMutableIndexSet removeIndexesInRange

Removes the indexes in an index range from the receiver.

- (void)removeIndexesInRange:(NSRange)indexRange

Parameters of [NSMutableIndexSet removeIndexesInRange]
indexRange
Index range to remove.

NSMutableIndexSet removeIndexesInRange example.
You may want to look at NSMutableIndexSet. It is designed to efficiently store ranges of numbers.

You can initialize it like this:

NSMutableIndexSet *set = [[NSMutableIndexSet alloc]
    initWithIndexesInRange:NSMakeRange(1, 100000)];
Then you can remove, for example, 123 from it like this:

[set removeIndex:123];
Or you can remove 400 through 409 like this:

[set removeIndexesInRange:NSMakeRange(400, 10)];
You can iterate through all of the remaining indexes in the set like this:

[set enumerateIndexesUsingBlock:^(NSUInteger i, BOOL *stop) {
    NSLog(@"set still includes %lu", (unsigned long)i);
}];
or, more efficiently, like this:

[set enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
    NSLog(@"set still includes %lu indexes starting at %lu",
        (unsigned long)range.length, (unsigned long)range.location);
}];

End of NSMutableIndexSet removeIndexesInRange example article.

NSMutableIndexSet removeIndexes example in Objective C (iOS).


NSMutableIndexSet removeIndexes

Removes the indexes in an index set from the receiver.

- (void)removeIndexes:(NSIndexSet *)indexSet

Parameters of [NSMutableIndexSet removeIndexes]
indexSet
Index set to remove.

NSMutableIndexSet removeIndexes example.
You may want to look at NSMutableIndexSet. It is designed to efficiently store ranges of numbers.

You can initialize it like this:

NSMutableIndexSet *set = [[NSMutableIndexSet alloc]
    initWithIndexesInRange:NSMakeRange(1, 100000)];
Then you can remove, for example, 123 from it like this:

[set removeIndex:123];
Or you can remove 400 through 409 like this:

[set removeIndexesInRange:NSMakeRange(400, 10)];
You can iterate through all of the remaining indexes in the set like this:

[set enumerateIndexesUsingBlock:^(NSUInteger i, BOOL *stop) {
    NSLog(@"set still includes %lu", (unsigned long)i);
}];
or, more efficiently, like this:

[set enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
    NSLog(@"set still includes %lu indexes starting at %lu",
        (unsigned long)range.length, (unsigned long)range.location);
}];

End of NSMutableIndexSet removeIndexes example article.

NSMutableIndexSet removeIndex example in Objective C (iOS).


NSMutableIndexSet removeIndex

Removes an index from the receiver.

- (void)removeIndex:(NSUInteger)index

Parameters of [NSMutableIndexSet removeIndex]
index
Index to remove.

NSMutableIndexSet removeIndex example.
You may want to look at NSMutableIndexSet. It is designed to efficiently store ranges of numbers.

You can initialize it like this:

NSMutableIndexSet *set = [[NSMutableIndexSet alloc]
    initWithIndexesInRange:NSMakeRange(1, 100000)];
Then you can remove, for example, 123 from it like this:

[set removeIndex:123];
Or you can remove 400 through 409 like this:

[set removeIndexesInRange:NSMakeRange(400, 10)];
You can iterate through all of the remaining indexes in the set like this:

[set enumerateIndexesUsingBlock:^(NSUInteger i, BOOL *stop) {
    NSLog(@"set still includes %lu", (unsigned long)i);
}];
or, more efficiently, like this:

[set enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) {
    NSLog(@"set still includes %lu indexes starting at %lu",
        (unsigned long)range.length, (unsigned long)range.location);
}];

Example of [NSMutableIndexSet removeIndex].
- (NSUInteger)indexForImageGivenIndexSet:(NSIndexSet*)indexSet             // Set of indexes you want to select from
                         prizeImageIndex:(NSUInteger)prizeIndex      // The prize index
                        probabilityScale:(CGFloat)probabilityScale   // The scale for the prize (8.0 for 8x less than the others)
{
    // If invalid, return what was given
    if (![indexSet containsIndex:prizeIndex]) {
        return prizeIndex;
    }

    // Calculate our probabilities
    // For a set of 4, with a scale of 8 on the prize, our probabilities would be
    // 0.04 (prize), 0.32, 0.32, 0.32
    double prizeProbability = (1.0 / indexSet.count) * (1.0 / probabilityScale);

    double val = (double)arc4random() / RAND_MAX;

    if (val < prizeProbability) {
        return prizeIndex;
    }
    else {
        // Select from the others in range equally
        NSMutableIndexSet* newSet = [[NSMutableIndexSet alloc] initWithIndexSet:indexSet];
        [newSet removeIndex:prizeIndex];

        NSInteger selectedPosition = arc4random() % newSet.count;
        __block NSInteger count = 0;
        return [newSet indexPassingTest:^BOOL(NSUInteger idx, BOOL *stop) {
            if (count == selectedPosition) {
                *stop = YES;
                return YES;
            }
            else {
                count++;
                return NO;
            }
        }];
    }
}

NSMutableIndexSet removeIndex example.
You will have to make subclass of the NSTableView class. This is basic example how you could do it. It handles selection with the spacebar and with the right mouse button, hoever it does not handle right mouse button drag selection.

The idea is to use NSTableView in single select mode and implement alternative selection. We add property markedRows and then use it instead of original selectedRows property.

FOTableView.h

#import <Cocoa/Cocoa.h>

@interface FOTableView : NSTableView

@property (strong,nonatomic) NSMutableIndexSet *markedRows;

@end
FOTableView.m

#import "FOTableView.h"

@implementation FOTableView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }

    return self;
}

-(NSMutableIndexSet *) markedRows
{
    if (!_markedRows) {
        _markedRows = [NSMutableIndexSet new];
    }
    return _markedRows;
}

- (void)drawRow:(NSInteger)row clipRect:(NSRect)clipRect
{
    if ([self.markedRows containsIndex:row]) {
        NSRect clipRect = [self rectOfRow:row];
        NSColor *color =  [NSColor colorWithCalibratedRed:0.932 green:0.046 blue:0.960 alpha:1.000];
        [color setFill];
        NSRectFill(clipRect);
    }

    [super drawRow:row clipRect:clipRect];
}

- (void)keyDown:(NSEvent *)theEvent
{
    NSString *keyString;
    unichar  keyChar;

    keyString = [theEvent charactersIgnoringModifiers];
    keyChar = [keyString characterAtIndex:0];
    NSInteger row = [self selectedRow];
    switch(keyChar){           
        case 32:
        {
             if (row != -1)
             {
                 if ([self.markedRows containsIndex:row]) {
                     [self.markedRows removeIndex:row];
                 }
                 else {
                     [self.markedRows addIndex:row];
                 }
             }
            [self selectRowIndexes:[NSIndexSet indexSetWithIndex:++row] byExtendingSelection:NO];
            [self setNeedsDisplay:YES];
            break;
        }

        default:
            [super keyDown:theEvent];
    }

    NSLog(@"key pressed: (%hu)%@", keyChar,keyString);
}

- (void)rightMouseDown:(NSEvent *)theEvent
{
    NSInteger row = [self rowAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]];
    if ([self.markedRows containsIndex:row]) {
        [self.markedRows removeIndex:row];
    }
    else {
        [self.markedRows addIndex:row];
    }

    [self setNeedsDisplay:YES];
}

@end

End of NSMutableIndexSet removeIndex example article.

NSMutableIndexSet removeAllIndexes example in Objective C (iOS).


NSMutableIndexSet removeAllIndexes

Removes the receiver’s indexes.

- (void)removeAllIndexes

NSMutableIndexSet removeAllIndexes example.
#import "NumberCreator.h"

@implementation NumberCreator
@synthesize levels, numbers;

- (id)init
{
    if ( !(self = [super init] ) )
        return nil;

    numbers = [NSMutableIndexSet new];
    return self;
}

- (void)create
{
    [numbers removeAllIndexes];
    [numbers addIndex:1];

    NSMutableIndexSet *nextLevel = [NSMutableIndexSet indexSet];
    NSMutableIndexSet *currentLevel = [NSMutableIndexSet indexSetWithIndex:1];

    for (int i = 0; i < levels; i++ )
    {
        [currentLevel enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {

            if ( ! [numbers containsIndex:idx * 2] )
                [nextLevel addIndex:idx * 2];

            if ( idx % 6 == 4 && ! [numbers containsIndex:(idx - 1) / 3] )
                [nextLevel addIndex:(idx - 1) / 3];
        }];

        [numbers addIndexes:nextLevel];
        [currentLevel removeAllIndexes];
        [currentLevel addIndexes:nextLevel];
        [nextLevel removeAllIndexes];
    }

    [numbers enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
        NSLog(@"%i", idx);
    }];
}

@end

Example of [NSMutableIndexSet removeAllIndexes].
//Not tested
//Assume that selectedIndexes is a NSMutableIndexSet
if ([selectedIndexes containsIndex:indexPath.row]) {
    if (self.options.count) {//This could probably be optimised depend on your goal
        [selectedIndexes addIndexesInRange:NSMakeRange(0,self.options.count-1)];
    } else {
        [selectedIndexes removeAllIndexes];
    }

NSMutableIndexSet removeAllIndexes example.
- (void)createFilteredTableGroups{

    //Checking for the usual suspects. all which may through an exception
    if(model==nil)
        return;
    if(tableGroups==nil)
        return;
    if([tableGroups count]==0)
        return;

    //lets make a new array to work with
    NSMutableArray *newTableGroups = [[allTableGroups mutableCopy] autorelease];

    //telling the table what we are about to do
    [self.tableView beginUpdates];

    //array to track cells for deletion animation
    NSMutableArray *indexesToRemove = [NSMutableArray array];

    //loop through each section
    for(NSMutableArray *eachSection in tableGroups){

        //keeping track of the indexes to delete for each section
        NSMutableIndexSet *indexesForSection = [NSMutableIndexSet indexSet];
        [indexesForSection removeAllIndexes];

        //increment though cell indexes
        int rowIndex = 0;

        //loop through each cellController in the section
        for(ScheduleCellController *eachCellController in eachSection){

            //Ah ha! A little magic. the cell controller must know if it should be displayed.
            //This you must calculate in your business logic
            if(![eachCellController shouldDisplay]){

                //add non-displayed cell indexes
                [indexesForSection addIndex:rowIndex];

            }
            rowIndex++;  
        }
        //adding each array of section indexes, EVEN if it is empty (no indexes to delete)
        [indexesToRemove addObject:indexesForSection];

    }

    //Now we remove cell controllers in newTableGroups and cells from the table
    //Also, each subarray of newTableGroups is mutable as well
    if([indexesToRemove count]>0){

        int sectionIndex = 0;
        for(NSMutableIndexSet *eachSectionIndexes in indexesToRemove){

            //Now you know why we stuck the indexes into individual arrays, easy array method
            [[newTableGroups objectAtIndex:sectionIndex] removeObjectsAtIndexes:eachSectionIndexes];

            //tracking which cell indexPaths to remove for each section
            NSMutableArray *indexPathsToRemove = [NSMutableArray array];
            int numberOfIndexes = [eachSectionIndexes count];

            //create array of indexPaths to remove
            NSUInteger index = [eachSectionIndexes firstIndex];
            for(int i = 0; i< numberOfIndexes; i++){

                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:sectionIndex];
                [indexPathsToRemove addObject:indexPath];
                index = [eachSectionIndexes indexGreaterThanIndex:index];
            }

            //delete the rows for this section
            [self.tableView deleteRowsAtIndexPaths:indexPathsToRemove withRowAnimation:UITableViewRowAnimationTop];

            //next section please
            sectionIndex++;
        }

    }

    //now we figure out if we need to remove any sections
    NSMutableIndexSet *sectionsToRemove = [NSMutableIndexSet indexSet];
    [sectionsToRemove removeAllIndexes];

    int sectionsIndex = 0;
    for(NSArray *eachSection in newTableGroups){

        //checking for empty sections
        if([eachSection count]==0)
            [sectionsToRemove addIndex:sectionsIndex];

        sectionsIndex++;
    }

    //updating the table groups
    [newTableGroups removeObjectsAtIndexes:sectionsToRemove];

    //removing the empty sections
    [self.tableView deleteSections:sectionsToRemove withRowAnimation:UITableViewRowAnimationTop];

    //updating filteredTableGroups to the newTableGroups we just created
    self.filteredTableGroups = newTableGroups;

    //pointing tableGroups at the filteredGroups
    tableGroups = filteredTableGroups;

    //invokes the animation
    [self.tableView endUpdates];

}

End of NSMutableIndexSet removeAllIndexes example article.

NSMutableIndexSet addIndexesInRange example in Objective C (iOS).


NSMutableIndexSet addIndexesInRange

Adds the indexes in an index range to the receiver.

- (void)addIndexesInRange:(NSRange)indexRange

Parameters
indexRange
Index range to add. Must include only indexes representable as unsigned integers.

Discussion of [NSMutableIndexSet addIndexesInRange]
This method raises an NSRangeException when indexRange would add an index that exceeds the maximum allowed value for unsigned integers.

NSMutableIndexSet addIndexesInRange example.
//Not tested
//Assume that selectedIndexes is a NSMutableIndexSet
if ([selectedIndexes containsIndex:indexPath.row]) {
    if (self.options.count) {//This could probably be optimised depend on your goal
        [selectedIndexes addIndexesInRange:NSMakeRange(0,self.options.count-1)];
    } else {
        [selectedIndexes removeAllIndexes];
    }

Example of [NSMutableIndexSet addIndexesInRange].
@autoreleasepool {
      
        // insert code here...
        NSLog(@"Hello, World!");
        NSRange indexRange = NSMakeRange(0, 6);
        NSMutableIndexSet *newIndexSet = [[NSMutableIndexSet alloc] initWithIndexesInRange:indexRange];
        for (int i=0; i<40; i++)
        {
            NSUInteger x = [newIndexSet oneTimeRandomIndex];
            if (x == NSNotFound)
            {
                                       // NSLog(@"newIndexSet needs to be refilled");
                [newIndexSet addIndexesInRange:indexRange];
                x = [newIndexSet oneTimeRandomIndex];
              
            }
            switch (x) {
                case 0:
                    NSLog(@"Cat");
                    break;
                case 1:
                    NSLog(@"Dog");
                    break;
                case 2:
                    NSLog(@"Fish");
                    break;
                case 3:
                    NSLog(@"Horse");
                    break;
                case 4:
                    NSLog(@"Bird");
                    break;
                case 5:
                    NSLog(@"Wombat");
                    break;  
                default:
                    break;
            }
          
        }

         NSLog(@"See Ya Later, World!");
    }
    return 0;

End of NSMutableIndexSet addIndexesInRange example article.