iosnsnetservicebrowser

NetServiceBrowser gives a different NetService when Removed


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?


Solution

  • 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: