代码之家  ›  专栏  ›  技术社区  ›  ACBurk

视图未更新

  •  0
  • ACBurk  · 技术社区  · 16 年前

    对iPhone编程有点陌生,正在尝试线程

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        [NSThread detachNewThreadSelector:@selector(changeMain) toTarget:self withObject:nil];
        [NSThread detachNewThreadSelector:@selector(changeThread) toTarget:self withObject:nil];
    }
    
    - (void)changeMain{
        NSAutoreleasePool* arp = [[NSAutoreleasePool alloc] init];
    
        for (int i = 0; i < 1000000; i++) {
            [mainValue setText:[NSString stringWithFormat:@"%d",i]];
            [self.view setNeedsDisplay];    
        }
    
        [arp release];
    }
    - (void)changeThread{
        NSAutoreleasePool* arp = [[NSAutoreleasePool alloc] init];
    
        for (int i = 0; i < 1000000; i++) {
            [threadValue setText:[NSString stringWithFormat:@"%d",i]];
            [self.view setNeedsDisplay];
        }
    
        [arp release];
    }
    

    4 回复  |  直到 16 年前
        1
  •  1
  •   rluba    16 年前
    1. 您必须在主线程中执行任何Cocoa Touch操作,在其他情况下,结果是不可预测的。
    2. 你不必打电话 setNeedsDisplay 手动。

    因此,我建议使用以下构造:

    [threadValue performSelectorOnMainThread:@selector(setText:) withObject:[NSString stringWithFormat:@"%d",i] waitUntilDone:YES];
    

    附加说明: 1.100000次运行可能会使主线程队列溢出,因此一些值将消失 2.您可以使用 waitUntilDone:NO

        2
  •  1
  •   Valerii Hiora    16 年前

    setNeedsDisplay 消息会触发重绘,但仅在下次主线程处于活动状态时发生。因此,你的侧线程会触发一百万次重绘,但它们会排队。一旦主线程继续,它就会将所有请求“折叠”为一次重绘。

    最可能 set需要显示

        3
  •  1
  •   mga    16 年前

    不使用 for() 用于动画。这 for ivar i 并且在 changeMain if (i<10000) { mainValue.text = [NSString stringWithFormat:@"%d",i]; i++;} 或者类似的东西。这边 setText

        4
  •  0
  •   MrMage    16 年前

    我不确定这是否可行,但你可以试着强迫 setNeedsDisplay 在主线程上执行的方法,使用例如。 [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES] 。这应该(希望我没有测试它!)在每次增量后更新视图。您也可以尝试设置 waitUntiDone:NO

    See here