我正在编写一个 XML 解析程序。解析过程运行良好,但我需要每 25 秒重复一次该函数。我试过 NSTimer
但它对我不起作用。当它被调用时,它会显示一个 SIGABRT 错误。下面给出了我需要每 25 秒调用一次的函数:
-(id)loadXMLByURL:(NSString *)filePath :(NSTimer *) timer
{
categories =[[NSMutableArray alloc]init];
NSData *myData = [NSData dataWithContentsOfFile:filePath];
parser =[[NSXMLParser alloc]initWithData:myData];
parser.delegate = self;
[parser parse];
return self;
}
下面给出了我用来设置定时器的方法
- (void)viewDidLoad
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cd_catalog" ofType:@"xml"];
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval: 25.0 target: self
selector: @selector(loadXMLByURL:filePath:) userInfo: nil repeats: YES];
xmlParser=[[XMLParser alloc] loadXMLByURL:filePath:myTimer];
[super viewDidLoad];
}
请告诉我我的代码有什么问题,并通过示例告诉我是否有任何其他方法可用于该过程。
提前致谢。
最佳答案
您用于定时器的选择器只能接受一个参数,那就是定时器。您不能将文件路径传递给计时器的选择器。
去掉 filePath 参数,使路径成为实例变量。
-(id)loadXML {
categories =[[NSMutableArray alloc]init];
NSData *myData = [NSData dataWithContentsOfFile:filePath]; // filePath is an ivar
parser =[[NSXMLParser alloc]initWithData:myData];
parser.delegate = self;
[parser parse];
return self;
}
- (void)viewDidLoad {
// filePath is now an ivar
filePath = [[NSBundle mainBundle] pathForResource:@"cd_catalog" ofType:@"xml"];
// The timer isn't needed by the selector so don't pass it
NSTimer* myTimer = [NSTimer scheduledTimerWithTimeInterval:25.0 target:self
selector:@selector(loadXML) userInfo:nil repeats:YES];
xmlParser=[[XMLParser alloc] loadXML];
[super viewDidLoad];
}
注意:您应该为每个参数命名。您的原始方法名为 loadXMLByURL::
。请注意中间没有任何内容的两个冒号。
关于ios - 如何在参数化函数中实现 NSTimer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15469616/