【问题标题】:iphone, how to refresh the gui?iphone,如何刷新gui?
【发布时间】:2010-08-17 22:01:26
【问题描述】:

我正在为 iphone 编写一个小应用程序(只是为了好玩)

我想要什么:

如果我按下“更新”按钮:

  • 向服务器发送一些东西
  • 解析服务器的答案
  • 更新屏幕上部分标签的内容
  • 显示答案
  • 播放系统声音 //使用音频工具箱
  • 睡几秒,刚好能完成之前的系统声音调用
  • 做其他事情
  • 结束

实际上,一切正常,但是...由于某种原因,标签内容在按下“更新”按钮时调用的方法/回调/函数结束时更新。

我做错了什么? 谢谢!

一些代码:

-(void) playASound: (NSString *) file {

    //Get the filename of the sound file:
    NSString *path = [NSString stringWithFormat:@"%@/%@",
                      [[NSBundle mainBundle] resourcePath],
                      file];

    SystemSoundID soundID;
    //Get a URL for the sound file
    NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
    AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
    //play the file
    AudioServicesPlaySystemSound(soundID);
}

- (IBAction)update: (id) sender{
    BOOL error=[self sendContent];
    if ( error == NO ){
        result.text=[self parseContent];
        [self playSound:@"ready"];
        sleep(4);
        ....
    }
// here is updated the gui
}

【问题讨论】:

    标签: iphone objective-c iphone-sdk-3.0


    【解决方案1】:

    GUI 由运行循环显示。在您的方法执行完毕之前,循环不会到达下一次迭代。因此,您的方法会阻止视图更新。使用后台线程或计时器。

    【讨论】:

    • 好的,感谢您的解释,我会尝试一个线程。 @tc:如果我这样做,由于音频内容是异步的,因此代码将继续......所以,想象一下:游戏(我的应用程序是游戏)将在你听指令之前开始......
    【解决方案2】:

    你不想在那里使用sleep。睡眠会阻止整个过程继续进行,这就是为什么您的标签仅在函数结束时更新的原因。我建议使用NSTimerperformSelector:withObject:afterDelay:(参见here)。

    【讨论】:

      【解决方案3】:

      这是因为你sleep时阻塞了主线程。 UI只能在主线程上绘制。

      一种解决方案是使用[NSTimer scheduledTimerWithTimeInterval:X_SEC target:self selector:@selector(doOtherStuff) userInfo:nil repeats:NO] 代替睡眠并做其他事情。

      【讨论】:

        【解决方案4】:

        在单独的线程中执行[self sendContent] 调用怎么样?

        【讨论】:

        • 不,它只是向服务器发送一堆数据的函数,它是同步的。
        猜你喜欢
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        • 2018-09-18
        • 2014-08-28
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 2012-03-09
        相关资源
        最近更新 更多