NSAlert *alert = [[NSAlert alloc] init];
// [alert addButtonWithTitle:@"OK"];
// [alert addButtonWithTitle:@"Cancel"];
[alert setMessageText:@"Test?"];
// [alert setInformativeText:@"Deleted records cannot be restored."];
// [alert setAlertStyle:NSWarningAlertStyle];
// [alert setHelpAnchor:@"ddd"];
// [alert beginSheetModalForWindow:_window
// modalDelegate:self
// didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:)
// contextInfo:nil];
[alert runModal];
常用樣式:NSInformationalAlertStyle、NSWarningAlertStyle、NSCriticalAlertStyle。
模態類型:runModal(應用級模態)、beginSheetModalForWindow:(窗口級工作表模態)。
CFOptionFlags result;
NSString *strMsg = [NSString stringWithFormat:@"%i", 234];
CFStringRef msgRef = (__bridge CFStringRef)strMsg;
CFUserNotificationDisplayAlert(
0, // timeout
kCFUserNotificationNoDefaultButtonFlag,
NULL, NULL, NULL, // icon, sound, localization
CFSTR("Title"), // 標題
CFSTR("Message"), // 內容
NULL, NULL, NULL, // 按鈕標題(NULL 使用默認)
&result); // 返回用戶點擊按鈕索引
適用場景:純 C/C++ 代碼中無 Objective-C 運行時、或需極簡單彈框無依賴 AppKit。
| 特性 | NSAlert | CFUserNotification |
|---|---|---|
| 語言 | Objective-C/Swift | C (Core Foundation) |
| 自定義程度 | 高(按鈕、圖標、輔助文字、樣式、工作表) | 低(基本標題/內容/按鈕) |
| 非阻塞 | 支援 Sheet 模態 | 僅阻塞模態 |
| 推薦度 | ★★★★★ | ★★☆☆☆ |