发送消息给另一个班级(Obj C)

时间:2010-07-18 19:11:49

标签: iphone objective-c

我有一个UITableViewController(OnTVViewController),它的viewDidLoad与下面类似(基本上在后台解析一些XML并在发生这种情况时显示一个活动指示符)。:

- (void)viewDidLoad {
OnTVXMLParser *xmlParser = [[OnTVXMLParser alloc] init];

/* Runs the parse command in the background */
[NSThread detachNewThreadSelector:@selector(parse) toTarget:xmlParser withObject:self];

//[xmlParser parse];

// new view to disable user interaction during downloading.
loadView = [[UIView alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
loadView.backgroundColor = [UIColor darkGrayColor];
//Loader spinner
UIActivityIndicatorView *act = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
[loadView addSubview:act]; 
act.center =loadView.center;
[self.view addSubview:loadView];
[self.view bringSubviewToFront:loadView];
[act startAnimating];
[act release];  

[super viewDidLoad];
}

OnTVViewController也有这个方法来删除活动指示器(只是在调试时尝试记录消息):

- (void)removeActivityView {
//[loadView removeFromSuperview];
NSLog(@"Should remove activity view here");
}

在我的OnTVXMLParser课程中,我有:

- (BOOL)parse{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Sleeping for 5 seconds");
[NSThread sleepForTimeInterval:5.0];
NSLog(@"Sleep finished");

// Simulated some elapsed time. I want to remove the Activity View
[self performSelectorOnMainThread:@selector(removeActivityView) withObject:nil waitUntilDone:false];

// Create and initialize an NSURL with the RSS feed address and use it to instantiate NSXMLParser
NSURL *url = [[NSURL alloc] initWithString:@"http://aurl.com/xml"];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

// Lots of parsing stuff snipped, this all runs fine

[pool release];
return YES;
}

基本上,一旦XMLParser类的“解析”方法完成,我想在OnTVViewController对象上调用removeActivityIndi​​cator。它可能非常简单,但我是iPhone编程的新手,并且碰到了我的头。

我知道我需要使用performSelectorOnMainThread - 但是如何引用我想要定位的OnTVViewController实例?我已将OnTVViewController头文件导入OnTVXMLParser。

目前我收到错误:

- [OnTVViewController removeActivityView:]:无法识别的选择器发送到实例0x8840ba0'

3 个答案:

答案 0 :(得分:0)

通常,cocoa使用委托模式处理此问题。基本上将一个ivar添加到名为delegate的XML解析器中,并启动parade将委托设置为self(OnTVViewController),然后将该委托用于XML解析器中的所有回调

答案 1 :(得分:0)

问题是选择器叫:

-[OnTVViewController removeActivityView:]: unrecognized selector sent to instance 0x8840ba0'

不存在。你告诉它调用这个选择器:

[self performSelectorOnMainThread:@selector(removeActivityView) withObject:nil waitUntilDone:false];

哪个不存在(请注意:),因为您的方法名为:

- (void)removeActivityView

尝试调用

- (void)removeActivityView:(id)dummy

看看会发生什么。

答案 2 :(得分:0)

您可能还想考虑使用NSNotificationCenter。这允许您为给定键(字符串)和选择器添加观察者,然后从应用程序的其他部分发布通知。

示例:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodToCall:) name:@"SomeKeyName" object:nil];

[[NSNotificationCenter defaultCenter] postNotificationName:@"SomeKeyName" object:nil];