Rubymotion Dispatch exiting early
-
11-06-2021 - |
Domanda
I'm executing a fairly vanilla dispatch queue in Rubymotion, however it is apparently exiting early. It never gets past the initWithContentsOfURL call. However, removing the Dispatch::Queue wrapper and putting the calls in the main thread works.
The application in the simulator exits with no stack trace or indication of what went wrong. Am I mis-using the dispatch queue?
def foo
Dispatch::Queue.concurrent.async do
error_ptr = Pointer.new(:object)
data = NSData.alloc.initWithContentsOfURL(
NSURL.URLWithString(url), options:NSDataReadingUncached, error:error_ptr)
unless data
p error_ptr[0]
return
end
json = NSJSONSerialization.JSONObjectWithData(data, options:0, error:error_ptr)
unless json
presentError error_ptr[0]
return
end
Dispatch::Queue.main.sync { print_results(json) }
end
end
def print_results(json)
p "#{json}"
end
Soluzione 2
I think I tracked down the issue. It was because I was declaring url in the method
def foo
url = "www.google.com"
Dispatch
take action on url
end
end
By moving the url declaration in to the Dispatch thread, it works. I think it was a matter of a method local variable going out of scope before the task had time to execute.
def foo
Dispatch
url = "www.google.com"
take action on url
end
end
Altri suggerimenti
Right now it seems that RubyMotion does not properly retain the local variables outside the dispatch block, so is probably getting an EXEC_BAD_ACCESS and crashing. The following fails:
foo = "some value"
Dispatch::Queue.concurrent.async do
puts foo
end
However the following two will work:
@foo = "some value"
Dispatch::Queue.concurrent.async do
puts @foo
end
and also:
foo = "some value"
foo.retain
Dispatch::Queue.concurrent.async do
puts foo
foo.release
end
In my case, declaring url in method was fine in RubyMotion 2.5, but my app was crashing with EXC_BAD_ACCESS
and sometimes with other error messages because of unicode characters in the app name and all over my code. Fixing encoding header and changing the app name solved my problem. Surprisingly, the app was working fine and crashed only when I called initWithContentsOfURL
.