Im trying to use NSThread so my display pic can load in the background so im calling it by开发者_如何学运维
[NSThread detachNewThreadSelector:@selector(displayPic:aURL :aURL2) toTarget:self withObject:nil];
But as im passing through 2 Strings, how would i construct this statement?
Thanks
Simple hack, use NSArray? Or use any other collection such as NSDictionary.
Example
NSArray *extraArgs = [[NSArray alloc] initWithObjects:string1, string2, nil];
[NSThread detachNewThreadSelector:@selector(displayPic:) toTarget:self withObject:extraArgs];
[extraArgs release];
There no proper way of doing this, as far as i am aware.
Pass an NSDictionary
built using all of the arguments needed by your function as the parameter.
[NSThread detachNewThreadSelector:@selector(displayPic:) toTarget:self withObject:
[NSDictionary dictionaryWithObjectsAndKeys: @"http://www.example.org/a.jpg", @"aURL", @"http://www.example.org/a.jpg", @"aURL2", nil]];
In the function you pass as a selector's code, you then retrieve from the dictionary the arguments you stored:
- (void) displayPic: (NSDictionary*)args
{
NSString *aURL = [args valueForKey: @"aURL"],
*aURL2 = [args valueForKey: @"aURL2"];
//The rest of the code
//...
}
Well:
There is a way of asynchronously calling arbitrary methods on objects that would go through NSOperationQueue
and I would highly recommend using operation-queues over NSThreads
most of the time.
Depending on the OS you are targeting (iPhone 3.x or iOS 4), this would be a one-liner or a lenghty chunk of code.
For iOS 4 behold the one-liner (assuming you have an NSOperationQueue
called queue
and your worker-object called worker
):
[queue addOperationWithBlock:^{ [worker displayPic:url1 :url2]; }];
Note that this works on OS X 10.6 as well.
The 3.x version would require you to either subclass NSOperation
or use NSInvocationOperation
-- which would have been what I originally wrote.
But here's the thing:
If all you want to do is prefetching something in the background, just modify your worker to only take one URL and use that with a queue to wich you add more of these fetchers.
Then the solutions becomes easy again on 2.x:
NSInvocationOperation *workerOperation = [[NSInvocationOperation alloc] initWithTarget:worker selector:@selector(displayURL:) object:url];
[queue addOperation:workerOperation]; // retains the operation
[workerOperation release];
Hope this helps
精彩评论