0

我创建了一个在新线程中运行的方法。

[NSThread detachNewThreadSelector:@selector(setmostpopularReq:) toTarget:self withObject:mostPopulerstring]; 

完成此方法后,我将所有数据发送到主线程。

[self performSelectorOnMainThread:@selector(getmostpopularResponse:) withObject:self waitUntilDone:YES];

但有时我的主线程方法没有调用。

我用了

dispatch_sync(dispatch_get_main_queue(),^{[self getmostpopularResponse:mostPopularList];});

但这也有同样的问题,有时它的调用方法或有时不调用。

请帮助我。

4

2 回答 2

0

我建议您创建一个委托,您可以在完成分离线程后通知主线程

另一种解决方案是创建一个 NSOperation 和 NSOperationQueue 而不是一个新线程。在那里你可以安排你想要的。对我来说看起来更容易,尽管这取决于你。

这是一个链接,可以帮助您更多地使用 NSOperation https://developer.apple.com/library/mac/#featuredarticles/ManagingConcurrency/_index.html

于 2012-12-10T12:22:05.070 回答
0

我会很快写这个的。

@protocol RespondDelegate
- (void)notifyWithRespond:(NSData *)data;
@end

@interface ContactWebServiceOperation:NSOperation
@property (nonatomic, assign) id delegate;
@end

@implementation ContactWebServiceOperation
@synthesize delegate;

// initialize here.
- (id)initWithDelegate:(id)delegate;
{
   if ([self = [super init]) { 
      self.delegate = delegate;
   }

   return self;
}

- (void)main 
{
    if (self.isCancelled) return;
    if (nil != delegate) {
        // Do your work here...
        work();

        // When finished notify the delegate with the new data.
        [delegate notifyWithRespond:your_data_here];

        // Or
        [delegate performSelectorOnMainThread:@selector(processImageForDownloadOperation:)
            withObject:self waitUntilDone:YES];
    }
}
@end



// Now on the view that you want to present the received results 
// you have to do one thing.
// Let's say that your view is called View1


@interface View1 : UIViewController<RespondDelegate>
// Here put whatever you like.
@end

@implementation View1

// Put here all your code.


- (void)notifyWithRespond:(NSData *)data
{
    // Here you will handle your new data and you will update your view.
}

@end

如果我理解正确,这应该有效。此外,您可以将 NSData 更改为您喜欢的任何内容,只要您稍后执行适当的转换即可。

如果它不起作用,请查看 Apple 的链接,也许我有一些错字或其他东西。但总的来说,它看起来很坚固。

于 2012-12-10T12:57:59.263 回答