performSelectorOnMainThread方法不能调用

时间:2012-12-10 11:24:33

标签: objective-c ios ios5 nsthread performselector

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

[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];});

但是这个问题在某个时候也有同样的问题,或者有些时候没有调用。

请帮助我。

2 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分: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的链接,也许我有一些错字或其他东西。 但总的来说它看起来很稳固。

相关问题