ios - 如何在参数化函数中实现 NSTimer?

标签 ios objective-c

我正在编写一个 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/

相关文章:

ios - 如何定义自定义 NSUnderlineStyle

ios - 对 bindTo 的模糊引用

c++ - 如何使用 break 语句停止内循环和外循环

ios - 如何解释 AudioBuffer 并获得权力?

ios - 显示 UIWebView 的键盘时向上移动 UIView

ios - Swift - 如何使 UILabel 像主题标签一样可点击并区分相同的文本?

ios - GPPSignIn 共享实例 -> EXC_BAD_ACCESS(代码 = EXC_I386_GPFLT)

由于搜索显示 Controller 检测到僵尸,iOS 7 应用程序崩溃

objective-c - UiScrollview滚动分页

objective-c - 黎曼和估计