
Objective-C实现程序等待一段时间(附完整源码)
在需要等待的地方添加以下代码:
发布日期:2025-04-26 23:56:16
浏览次数:3
分类:精选文章
本文共 1975 字,大约阅读时间需要 6 分钟。
在 Objective-C 中实现程序等待一段时间,通常可以通过 NSTimer 或 dispatch_after 方法来实现。本文将详细介绍如何在 macOS 或 iOS 应用中实现这一功能。
项目配置
首先,需要在 Xcode 中创建一个新的项目。选择 macOS > App 或 iOS > App 模板。在项目中,添加一个 UILabel(iOS)或 NSTextField(macOS)用于显示信息,和一个 UIButton(iOS)或 NSButton(macOS)用于触发等待操作。
界面设计
在 Main.storyboard 中,添加以下元素:
- 一个 UILabel(或 NSTextField),用于显示等待状态。
- 一个 UIButton(或 NSButton),设置标题为 “开始等待”。
代码实现
AppDelegate.h(macOS)
在 AppDelegate.h 文件中,声明必要的属性和方法。
#import@interface AppDelegate : NSObject@property (nonatomic, strong) NSTextField *waitStatus;@property (nonatomic, strong) NSButton *startButton;- (void)startWaiting;- (void)timerDidFire:(NSTimer *)timer;@end
AppDelegate.m(macOS)
在 AppDelegate.m 文件中,实现相关逻辑。
#import "AppDelegate.h"@implementation AppDelegate- (void)startWaiting { [self.startButton setEnabled:NO]; [self.waitStatus setStringValue:@"正在等待..."]; // 使用 NSTimer 实现等待 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerDidFire:) userInfo:nil repeats:YES]; [timer fire];}- (void)timerDidFire:(NSTimer *)timer { [self.waitStatus setStringValue:[[self.waitStatus stringValue] appendAttributedString:[[NSAttributedString alloc] initWithString:@"."]]; if (timer.tolerance < 1) { [timer invalidate]; [self.startButton setEnabled:YES]; [self.waitStatus setStringValue:@"等待完成"]; }}- (void)ApplicationDidFinishLoading { [self.waitStatus setStringValue:@""];}
使用 dispatch_after 方法(iOS)
如果需要在 iOS 中使用 dispatch_after 方法来实现等待,可以按照以下步骤操作:
dispatch_after(dispatch_time(1000.0, 0.0), dispatch_get_main_queue(), ^{ // 你的等待逻辑});
- 例如,修改上述代码以实现等待 2 秒:
dispatch_after(dispatch_time(1000.0, 0.0), dispatch_get_main_queue(), ^{ [self.startButton setEnabled:YES]; [self.waitStatus setStringValue:@"等待完成"];});
总结
在 Objective-C 中,实现程序等待一段时间可以通过多种方法,包括使用 NSTimer 或 dispatch_after。选择合适的方法取决于你的具体需求和应用场景。通过以上方法,你可以轻松实现等待功能,并根据需要进行适当的调整。
发表评论
最新留言
不错!
[***.144.177.141]2025年04月27日 15时18分47秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!