NetServiceBrowser gives a different NetService when Removed

1k Views Asked by At

I was hoping to do something like this:

In netServiceBrowser:didFindService:moreComing:

[self.foundServices addObject:aNetService];

And in netServiceBrowser:didRemoveService:moreComing:

[self.foundServices removeObject:aNetService];

However, the services returned aren't retained by the NetServiceBrowser, and so the service given in didRemoveService isn't the same object as those in the array. How do I compare the services to ensure that the one I remove is the correct one?

2

There are 2 best solutions below

3
On BEST ANSWER

You're over-thinking this, and creating a problem in your head that doesn't exist. Use removeObject: on the object passed into didRemoveService:. removeObject: removes based on the object's response to isEqual:, not the address or identity of the object. So this will just work.

The answer really is as simple as:

[self.foundServices removeObject:aNetService];

Apple's description of removeObject: explains this:

This method uses indexOfObject: to locate matches and then removes them by using removeObjectAtIndex:. Thus, matches are determined on the basis of an object’s response to the isEqual: message.

(For completeness, Apple does offer a function that removes an object by address. That's removeObjectIdenticalTo:. That's not the behaviour you want here, however. Just use removeObject:.)

References:

1
On

Short answer, I ended up having to use this, but I can't reproduce the problem anymore. Use the selected answer.

- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didFindService:(NSNetService *)aNetService moreComing:(BOOL)moreComing {
    [self.foundServices addObject:aNetService];
}


- (void)netServiceBrowser:(NSNetServiceBrowser *)aNetServiceBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)moreComing {
    NSNetService *found = nil;

    for(NSNetService *ns in self.foundServices) {
        if([ns isEqualTo:aNetService]) {
            found = ns;
        }
    }

    if(found) {
        [self.foundServices removeObject:found];
    }
}