【问题标题】:calling method from NSThread从 NSThread 调用方法
【发布时间】:2012-05-19 02:22:27
【问题描述】:

我试图在我的应用程序中调用一个类方法:didFinishLaunchingWithOptions: using NSThread。但奇怪的是,这个方法没有被调用。我在 didFinishLaunchingWithOptions 方法中尝试了以下方法。

[self performSelector:@selector(parseAdContent) onThread:myThread withObject:AdvertisementView waitUntilDone:NO];
      [myThread start];

帮帮我。

【问题讨论】:

  • 确保这个方法在同一个类中。
  • 你想在主线程中调用它吗?
  • AdvertisingView 是一个类还是一个类的实例?
  • 我不想在主线程中调用它。想在后台进行这个过程。@@tronbabylove 类的 Saad 实例
  • 是的,它在同一个班级。任何其他帮助将不胜感激。

标签: iphone ios ios5 methods nsthread


【解决方案1】:

这是创建单独线程的方式:

[NSThread detachNewThreadSelector:@selector(yourSelector:) toTarget:yourTarget withObject:objectYouWishToPassAsParameter];

您指定的选择器将自动在新线程上执行。

您的代码的特定示例:

[NSThread detachNewThreadSelector:@selector(parseAdContent:) toTarget:self withObject:AdvertisementView];

你的线程选择器应该是这样的:

- (void)parseAdContent:(id)obj {
    NSAutoreleasePool *threadPool = [[NSAutoreleasePool alloc] init];
    // Your background thread code here

    [pool drain];
}

【讨论】:

  • OP 说他正在尝试调用类方法。目标不应该是 [self class] 吗?
  • @tronbabylove 感谢您的回复,但我没有得到预期的结果。目标不能是 self 或 self 类,为什么因为我在另一个名为 Adview 的类中有该方法,其中 AdvertisementView 是 applicationDelagate 类中该类的实例变量。请再帮忙
  • @user1188275 它位于 Adview 类中 - 那么它是类方法还是实例方法?
  • 对于我上面使用的方法示例 (- (void)parseAdContent:(id)obj),目标是 self,而不是 [self class]。如果您要使用静态方法(例如:+ (id)someMethod:(id)param),则目标确实是 [self class]。我的例子应该已经足够描述]
【解决方案2】:

你想调用一个类方法,但是这个调用试图调用自己的 -parseAdContent:。我不知道这是在哪个类中调用的,但无论哪种方式,这里的目标都是实例变量 self 而不是类。像这样的东西可能更符合您的要求。

[myThread initWithTarget:[self class] selector:@selector(parseAdContent) object:AdvertisementView];

编辑:所以如果方法是 Adview 类中的类方法,只需将目标更改为 Adview 类...

[myThread initWithTarget:[Adview class] selector:@selector(parseAdContent) object:AdvertisementView];

但是如果是Adview类中的实例方法,那么目标就是Adview类型变量的实例——AdvertisingView,对吧?

[myThread initWithTarget:AdvertisementView selector:@selector(parseAdContent) object:AdvertisementView];

但这没有意义,您不会调用实例方法并将实例作为参数传递给它自己的方法...目标是您为其调用选择器的对象。 object: 参数用于选择器的参数。

我假设这是您最初所说的类方法,在这种情况下,这两个调用中的第一个应该可以工作。

【讨论】:

  • 我尝试了你的两个示例,将我的方法作为类和实例方法,但执行周期没有通过该方法。我完全迷失了。在过去的两天里解决了这个问题!感谢您的回复。
  • @user1188275 我注意到的另一件事是您将参数传递给方法 (AdvertisementView),但您没有在选择器标记中包含“:”。它应该是“selector:(parseAdContent:)”我认为添加冒号使它成为一个完全不同的选择器 - 尝试添加它,看看它是否会改变任何东西。
  • @user1188275 还有一点需要注意 - 根据 Apple Docs,“选择器必须只接受一个参数,并且不能有返回值。”所以请确保 parseAdContent 没有返回任何内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 2013-09-16
  • 2015-08-29
相关资源
最近更新 更多