views:

287

answers:

2

I'm trying to resolve a NSNetService (named "My_Mac") to an IP in a background app with this code:

NSNetService *service = [[NSNetService alloc] initWithDomain:@"local." type:@"_daap._tcp" name:@"My_Mac"];
[service setDelegate:self];
[service resolveWithTimeout:5];

And in the same class, I have these delegate methods defined:

- (void)netServiceDidResolveAddress:(NSNetService *)sender
- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict

Here's the strange part: neither delegate methods get called unless I run a NSAlert after "[service resolveWithTimeout:5];". Any ideas?

+1  A: 

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?

EDIT: I had another thought that this might be some kind of race condition (a more likely scenario). Delegates are usually weak references. If your object is dropping out of scope and being autoreleased, the system would end up with a nil handle and be firing the messages to nil. In the case where you show an NSAlert (or do other work) your object might be hanging around just long enough for it to get the messages fired back to it. Could you confirm your object sticks around for the full 8 seconds?

slf
Thanks for the reply slf. I tried the NSRunLoop code you had, but no dice. I just have the methods since I'm targeting 10.5 which doesn't have the formal NSServiceDelegate protocol defined.
K_T
slf: you're right - I turned off GC to make sure the object was still there, and the delegates were called. Now I just have to track down where it's being autoreleased, since I've explicitly tried retaining it, and that didn't work. Thanks for pointing me in the right direction!
K_T
the solution to seemingly complex problems is usually simpler than you first think :)
slf
An explicit retain of the `NSNetService` object right after `resolveWithTimeout` fixed the same problem for me, too. I'm new to iPhone development, but damn! stuff like this is irritating. I guess the motto for Mac/iPhone programming should be "it just doesn't work".
MusiGenesis
+1  A: 

Thank you, I never cease to be amazed at how often Stack Overflow has the -exact- question I'm having at the moment - for me, an explicit retain did it!

Thanks!

buffpojken