Objective c performSelectorOnMainThread方法未调用
我已经创建了一个在新线程中运行的方法Objective c performSelectorOnMainThread方法未调用,objective-c,ios,ios5,nsthread,performselector,Objective C,Ios,Ios5,Nsthread,Performselector,我已经创建了一个在新线程中运行的方法 [NSThread detachNewThreadSelector:@selector(setmostpopularReq:) toTarget:self withObject:mostPopulerstring]; 完成此方法后,我将所有数据发送到主线程 [self performSelectorOnMainThread:@selector(getmostpopularResponse:) withObject:self waitUntilDone:Y
[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];});
但这也是有一段时间它的调用方法或者有一段时间不调用的问题
请在这方面帮助我。我建议您创建一个委托,您可以在事件发生后通知主线程 完成分离的线程 另一种解决方案是创建NSOperation和NSOperationQueue,而不是创建新线程。在那里你可以安排你想要的。对我来说看起来更容易,尽管这取决于你 这里有一个链接可以帮助您更好地了解NSO操作
我会很快写下来
@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
@协议响应委托
-(void)notifyWithRespond:(NSData*)数据;
@结束
@接口ContactWebServiceOperation:NSOperation
@属性(非原子,赋值)id委托;
@结束
@实现ContactWebServiceOperation
@综合代表;
//在这里初始化。
-(id)initWithDelegate:(id)delegate;
{
如果([self=[super init]){
self.delegate=委托;
}
回归自我;
}
-(无效)主要
{
如果(自我取消)返回;
如果(无!=委托){
//在这里做你的工作。。。
工作();
//完成后,使用新数据通知代理。
[代表通知回复:此处为您的数据];
//或
[委托performSelectorOnMainThread:@selector(processImageForDownloadOperation:)
with object:self waiting直到done:YES];
}
}
@结束
//现在在视图上,您希望显示收到的结果
//你必须做一件事。
//假设您的视图称为View1
@界面视图1:UIViewController
//你喜欢什么就放什么。
@结束
@实现视图1
//把你所有的代码都放在这里。
-(void)notifyWithRespond:(NSData*)数据
{
//在这里,您将处理新数据并更新视图。
}
@结束
如果我理解正确,这应该是可行的。
此外,只要稍后执行适当的转换,您可以将NSData更改为任何您喜欢的格式
如果它不起作用,看看苹果的链接,也许我有一些打字错误或什么的。
但总的来说,它看起来很可靠。我认为GCD没有被破坏,那么您如何验证该方法是否被调用?我使用断点跟踪。它没有调用这些“getmostpopularResponse”在完成所有功能后,我的事件不会出现在前台,它必须是从那里开始的,但它不起作用。感谢您的回复。请给我一个简单的例子。我的要求是我必须在后台发送一个webservice调用,以便我可以在字体上执行一些事件,在收到回复后,我将在前台显示响应数据。