创建没有NIB文件的Cocoa应用程序

时间:2010-06-08 12:44:28

标签: xcode cocoa project

是的,我知道这违反了整个MVC原则!

然而,我只是试图掀起一个非常简单的应用程序 - 而且我已经实现了它。但是,我有一个问题...

我创建一个空项目,复制所有框架并设置构建设置 - 我得到有关可执行文件或缺少可执行文件的错误。构建设置都显得很好,但它告诉我没有可执行文件 - 它将构建+运行正常。但是它没有运行。也没有任何错误 - 它似乎运行非常快速和干净!除非我尝试运行GDB,礼貌地告诉我,我需要先给它一个文件..

Running…  
No executable file specified.  
Use the "file" or "exec-file" command.

所以我创建了一个Cocoa应用程序,删除了所有我不需要的东西(即MainMenu.xib文件..),现在我可以完美地编译我的代码了。然而它死于抱怨它是

  

“无法加载nib文件:MainMenu,退出”

我已经浏览了项目符号,并且看到代码实际上严重依赖于NIB文件,即使您没有按代码方式触摸它。 (我猜再次MVC)。

是否有一种简单的方法来编译你编码的内容,没有添加的NIB文件,只是你编写的代码和你添加的框架?我认为这将是一个空白的项目,但我的经验告诉我不是吗?!

11 个答案:

答案 0 :(得分:34)

这是我在我的应用程序中使用的方法。对不起格式化,我希望你能搞定。我不知道如何在这里关闭自动格式化。

当然这个例子中没有正常运行的主菜单,这对我来说写的代码太多了:P - 抱歉,对此进行一些研究;)

这应该让你开始:

<强> AppDelegate.h

@interface MyApplicationDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {
    NSWindow * window;
}
@end

<强> AppDelegate.m

@implementation MyApplicationDelegate : NSObject
- (id)init {
    if (self = [super init]) {
        // allocate and initialize window and stuff here ..
    }
    return self;
}

- (void)applicationWillFinishLaunching:(NSNotification *)notification {
    [window makeKeyAndOrderFront:self];
}

- (void)dealloc {
    [window release];
    [super dealloc];
}

@end

<强>的main.m

#import "AppDelegate.h"

int main(int argc, char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSApplication * application = [NSApplication sharedApplication];

    MyApplicationDelegate * appDelegate = [[[[MyApplicationDelegate]alloc] init] autorelease];

    [application setDelegate:appDelegate];
    [application run];

    [pool drain];

    return EXIT_SUCCESS;
}

答案 1 :(得分:21)

int main() {
    [NSAutoreleasePool new];
    [NSApplication sharedApplication];
    [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id appName = [[NSProcessInfo processInfo] processName];
    id quitTitle = [@"Quit " stringByAppendingString:appName];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:quitTitle
    action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
    id window = [[[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 200, 200)
    styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO]
    autorelease];
    [window cascadeTopLeftFromPoint:NSMakePoint(20,20)];
    [window setTitle:appName];
    [window makeKeyAndOrderFront:nil];
    [NSApp activateIgnoringOtherApps:YES];
    [NSApp run];
    return 0;
}

答案 2 :(得分:10)

当然,您只需编写代码而不使用Interface Builder。

您检查过Info.plist吗?默认情况下,MainMenu.xib有一个条目,它可能是它抱怨的引用。

答案 3 :(得分:10)

虽然这是几年的问题......

这是在Swift中引导Cocoa应用程序的最小代码片段。

import AppKit

final class ExampleApplicationController: NSObject, NSApplicationDelegate {
    let window1 =   NSWindow()

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        window1.setFrame(CGRect(x: 0, y: 0, width: 800, height: 500), display: true)
        window1.makeKeyAndOrderFront(self)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
    }

}

autoreleasepool { () -> () in
    let app1        =   NSApplication.sharedApplication()
    let con1        =   ExampleApplicationController()

    app1.delegate   =   con1
    app1.run()
}

另外,我正在为Cocoa维护一系列程序化示例,包括自举,窗口,菜单创建。

请参阅子项目以获取所需语言。

答案 4 :(得分:7)

问题可能是您仍然在NSApplicationMain函数中调用main(在main.m中)。如果您没有加载MainMenu.nib这样的笔尖,则可能需要删除对NSApplicationMain的调用,并在main中编写自己的代码以启动应用程序。

答案 5 :(得分:5)

带有NSToolbarNSMenu的Swift 4版本(使用事件处理程序代替委托):

档案 main.swift

autoreleasepool {
   // Even if we loading application manually we need to setup `Info.plist` key:
   // <key>NSPrincipalClass</key>
   // <string>NSApplication</string>
   // Otherwise Application will be loaded in `low resolution` mode.
   let app = Application.shared
   app.setActivationPolicy(.regular)
   app.run()
}

文件: Application.swift

class Application: NSApplication {

   private lazy var mainWindowController = MainWindowController()
   private lazy var mainAppMenu = MainMenu()

   override init() {
      super.init()
      setupUI()
      setupHandlers()
   }

   required init?(coder: NSCoder) {
      super.init(coder: coder) // This will never called.
   }
}

extension Application: NSApplicationDelegate {

   func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
      return true
   }

   func applicationDidFinishLaunching(_ aNotification: Notification) {
      mainWindowController.showWindow(nil)
   }

}

extension Application {

   private func setupUI() {
      mainMenu = mainAppMenu
   }

   private func setupHandlers() {
      delegate = self
      mainAppMenu.eventHandler = { [weak self] in
         switch $0 {
         case .quit:
            self?.terminate(nil)
         }
      }
   }

}

档案 MainWindowController.swift

class MainWindowController: NSWindowController {

   private (set) lazy var viewController = MainViewController()
   private (set) lazy var mainToolbar = MainToolbar(identifier: NSToolbar.Identifier("ua.com.wavelabs.Decoder:mainToolbar"))

   init() {
      let window = NSWindow(contentRect: CGRect(x: 400, y: 200, width: 800, height: 600),
                            styleMask: [.titled, .closable, .resizable, .miniaturizable],
                            backing: .buffered,
                            defer: true)
      super.init(window: window)


      let frameSize = window.contentRect(forFrameRect: window.frame).size
      viewController.view.setFrameSize(frameSize)
      window.contentViewController = viewController

      window.titleVisibility = .hidden
      window.toolbar = mainToolbar

      setupHandlers()
   }

   required init?(coder: NSCoder) {
      super.init(coder: coder)
   }
}

extension MainWindowController {

   private func setupHandlers() {
      mainToolbar.eventHandler = {
         print($0)
      }
   }
}

文件 MainViewController.swift

class MainViewController: NSViewController {

   init() {
      super.init(nibName: nil, bundle: nil)
   }

   required init?(coder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
   }

   override func loadView() {
      view = NSView()
      view.wantsLayer = true
      view.layer?.backgroundColor = NSColor.magenta.cgColor
   }
}

档案 MainToolbar.swift

class MainToolbar: NSToolbar {

   enum Event: Int {
      case toggleSidePanel
   }

   let toolbarDelegate = GenericDelegate()

   var eventHandler: ((MainToolbar.Event) -> Void)?

   override init(identifier: NSToolbar.Identifier) {
      super.init(identifier: identifier)
      setupUI()
      setupHandlers()
   }
}

extension MainToolbar {

   private func setupUI() {
      allowsUserCustomization = true
      autosavesConfiguration = true
      displayMode = .iconOnly
      toolbarDelegate.allowedItemIdentifiers = [.space, .flexibleSpace]
      toolbarDelegate.selectableItemIdentifiers = [.space, .flexibleSpace]
      toolbarDelegate.defaultItemIdentifiers = Event.toolbarIDs + [.flexibleSpace]
   }

   private func setupHandlers() {
      delegate = toolbarDelegate
      toolbarDelegate.makeItemCallback = { [unowned self] id, _ in
         guard let event = Event(id: id) else {
            return nil
         }
         return self.makeToolbarItem(event: event)
      }
   }

   private func makeToolbarItem(event: Event) -> NSToolbarItem {
      let item = NSToolbarItem(itemIdentifier: event.itemIdentifier)
      item.setHandler { [weak self] in
         guard let event = Event(id: event.itemIdentifier) else {
            return
         }
         self?.eventHandler?(event)
      }
      item.label = event.label
      item.paletteLabel = event.paletteLabel
      if event.image != nil {
         item.image = event.image
      } else if event.view != nil {
         item.view = event.view
      }
      return item
   }
}

extension MainToolbar.Event {

   init?(id: NSToolbarItem.Identifier) {
      guard let event = (MainToolbar.Event.allValues.filter { $0.itemIdentifier == id }).first else {
         return nil
      }
      self = event
   }

   static var allValues: [MainToolbar.Event] {
      return [toggleSidePanel]
   }

   static var toolbarIDs: [NSToolbarItem.Identifier] {
      return [toggleSidePanel].map { $0.itemIdentifier }
   }

   var itemIdentifier: NSToolbarItem.Identifier {
      switch self {
      case .toggleSidePanel: return NSToolbarItem.Identifier("ua.com.wavalabs.toolbar.toggleSidePanel")
      }
   }

   var label: String {
      switch self {
      case .toggleSidePanel: return "Toggle Side Panel"
      }
   }

   var view: NSView? {
      return nil
   }

   var image: NSImage? {
      switch self {
      case .toggleSidePanel: return NSImage(named: NSImage.Name.folder)
      }
   }

   var paletteLabel: String {
      return label
   }
}

档案 MainMenu.swift

class MainMenu: NSMenu {

   enum Event {
      case quit
   }

   var eventHandler: ((Event) -> Void)?

   private lazy var applicationName = ProcessInfo.processInfo.processName

   init() {
      super.init(title: "")
      setupUI()
   }

   required init(coder decoder: NSCoder) {
      super.init(coder: decoder)
   }

}


extension MainMenu {

   private func setupUI() {

      let appMenuItem = NSMenuItem()
      appMenuItem.submenu = appMenu

      addItem(appMenuItem)
   }

   private var appMenu: NSMenu {
      let menu = NSMenu(title: "")
      menu.addItem(title: "Quit \(applicationName)", keyEquivalent: "q") { [unowned self] in
         self.eventHandler?(.quit)
      }
      return menu
   }

}

便利扩展

档案 NSMenu.swift

extension NSMenu {

   @discardableResult
   public func addItem(title: String, keyEquivalent: String, handler: NSMenuItem.Handler?) -> NSMenuItem {
      let item = addItem(withTitle: title, action: nil, keyEquivalent: keyEquivalent)
      item.setHandler(handler)
      return item
   }

}

档案 NSMenuItem.swift

extension NSMenuItem {

   public typealias Handler = (() -> Void)

   convenience init(title: String, keyEquivalent: String, handler: Handler?) {
      self.init(title: title, action: nil, keyEquivalent: keyEquivalent)
      setHandler(handler)
   }

   public func setHandler(_ handler: Handler?) {
      target = self
      action = #selector(wavelabsActionHandler(_:))
      if let handler = handler {
         ObjCAssociation.setCopyNonAtomic(value: handler, to: self, forKey: &OBJCAssociationKeys.actionHandler)
      }
   }

}

extension NSMenuItem {

   private struct OBJCAssociationKeys {
      static var actionHandler = "com.wavelabs.actionHandler"
   }

   @objc private func wavelabsActionHandler(_ sender: NSControl) {
      guard sender == self else {
         return
      }
      if let handler: Handler = ObjCAssociation.value(from: self, forKey: &OBJCAssociationKeys.actionHandler) {
         handler()
      }
   }
}

档案 NSToolbar.swift

extension NSToolbar {

   class GenericDelegate: NSObject, NSToolbarDelegate {

      var selectableItemIdentifiers: [NSToolbarItem.Identifier] = []
      var defaultItemIdentifiers: [NSToolbarItem.Identifier] = []
      var allowedItemIdentifiers: [NSToolbarItem.Identifier] = []

      var eventHandler: ((Event) -> Void)?
      var makeItemCallback: ((_ itemIdentifier: NSToolbarItem.Identifier, _ willBeInserted: Bool) -> NSToolbarItem?)?
   }
}

extension NSToolbar.GenericDelegate {

   enum Event {
      case willAddItem(item: NSToolbarItem, index: Int)
      case didRemoveItem(item: NSToolbarItem)
   }
}

extension NSToolbar.GenericDelegate {

   func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier,
                willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
      return makeItemCallback?(itemIdentifier, flag)
   }

   func toolbarDefaultItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
      return defaultItemIdentifiers
   }

   func toolbarAllowedItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
      return allowedItemIdentifiers
   }

   func toolbarSelectableItemIdentifiers(_: NSToolbar) -> [NSToolbarItem.Identifier] {
      return selectableItemIdentifiers
   }

   // MARK: Notifications

   func toolbarWillAddItem(_ notification: Notification) {
      if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem,
         let index = notification.userInfo?["newIndex"] as? Int {
         eventHandler?(.willAddItem(item: toolbarItem, index: index))
      }
   }

   func toolbarDidRemoveItem(_ notification: Notification) {
      if let toolbarItem = notification.userInfo?["item"] as? NSToolbarItem {
         eventHandler?(.didRemoveItem(item: toolbarItem))
      }
   }
}

档案 NSToolbarItem.swift

extension NSToolbarItem {

   public typealias Handler = (() -> Void)

   public func setHandler(_ handler: Handler?) {
      target = self
      action = #selector(wavelabsActionHandler(_:))
      if let handler = handler {
         ObjCAssociation.setCopyNonAtomic(value: handler, to: self, forKey: &OBJCAssociationKeys.actionHandler)
      }
   }

}

extension NSToolbarItem {

   private struct OBJCAssociationKeys {
      static var actionHandler = "com.wavelabs.actionHandler"
   }

   @objc private func wavelabsActionHandler(_ sender: NSControl) {
      guard sender == self else {
         return
      }
      if let handler: Handler = ObjCAssociation.value(from: self, forKey: &OBJCAssociationKeys.actionHandler) {
         handler()
      }
   }
}

档案 ObjCAssociation.swift

public struct ObjCAssociation {

   public static func value<T>(from object: AnyObject, forKey key: UnsafeRawPointer) -> T? {
      return objc_getAssociatedObject(object, key) as? T
   }

   public static func setAssign<T>(value: T?, to object: Any, forKey key: UnsafeRawPointer) {
      objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_ASSIGN)
   }
   public static func setRetainNonAtomic<T>(value: T?, to object: Any, forKey key: UnsafeRawPointer) {
      objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
   }
   public static func setCopyNonAtomic<T>(value: T?, to object: Any, forKey key: UnsafeRawPointer) {
      objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_COPY_NONATOMIC)
   }
   public static func setRetain<T>(value: T?, to object: Any, forKey key: UnsafeRawPointer) {
      objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN)
   }
   public static func setCopy<T>(value: T?, to object: Any, forKey key: UnsafeRawPointer) {
      objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_COPY)
   }
}

答案 6 :(得分:3)

以下是Casper's solution,根据Marco's suggestion针对ARC进行了更新:

#import <Cocoa/Cocoa.h>
#import "AppDelegate.h"

int main(int argc, char * argv[]) {
    @autoreleasepool {
        NSApplication *application = [NSApplication sharedApplication];
        AppDelegate *appDelegate = [[AppDelegate alloc] init];
        [application setDelegate:appDelegate];
        [application run];
    }
    return EXIT_SUCCESS;
}

答案 7 :(得分:3)

参加派对已经晚了7年,但单个文件代码更简单

#import <Cocoa/Cocoa.h>

@interface AppDelegate : NSObject <NSApplicationDelegate, NSWindowDelegate> {
    NSWindow* window;
}
@end

@implementation AppDelegate : NSObject
- (id)init {
    if (self = [super init]) {
        window = [NSWindow.alloc initWithContentRect: NSMakeRect(0, 0, 200, 200)
                                           styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskClosable
                                             backing: NSBackingStoreBuffered
                                               defer: NO];
    }
    return self;
}

- (void)applicationWillFinishLaunching:(NSNotification *)notification {
    window.title = NSProcessInfo.processInfo.processName;
    [window cascadeTopLeftFromPoint: NSMakePoint(20,20)];
    [window makeKeyAndOrderFront: self];
}

@end

int main(int argc, const char * argv[]) {
    NSApplication* app = NSApplication.sharedApplication;
    app.ActivationPolicy = NSApplicationActivationPolicyRegular;
    NSMenuItem* item = NSMenuItem.new;
    NSApp.mainMenu = NSMenu.new;
    item.submenu = NSMenu.new;
    [app.mainMenu addItem: item];
    [item.submenu addItem: [[NSMenuItem alloc] initWithTitle: [@"Quit " stringByAppendingString: NSProcessInfo.processInfo.processName] action:@selector(terminate:) keyEquivalent:@"q"]];
    AppDelegate* appDelegate = AppDelegate.new; // cannot collapse this and next line because .dlegate is weak
    app.delegate = appDelegate;
    (void)app.run;
    return 0;
}

答案 8 :(得分:0)

autoreleasepool片段provided above的示例swift代码在现代Xcode中不起作用。相反,您需要删除App Delegate源文件中的@NSApplicationMain(如果有的话)(Xcode现在为新项目添加这些),并添加包含以下内容的main.swift文件:

上面的顶级代码示例不再适用于最新版本的Xcode。而是使用它:

import Cocoa

let delegate = ExampleApplicationController() //alloc main app's delegate class
NSApplication.shared().delegate = delegate //set as app's delegate

let ret = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)

答案 9 :(得分:0)

当然,回答这个问题为时已晚,但对于那些考虑创建没有Xib(Nib)文件的iOS应用程序的人来说应该记住这一点。

  

注意:虽然您可以在不使用nib文件的情况下创建Objective-C应用程序,但这样做非常罕见,不推荐使用。根据您的应用程序,避免使用nib文件可能需要您替换大量的框架行为,以获得与使用nib文件相同的结果。

See this Documentation to know more what apple has to say on this approach

我希望这可以在将来帮助某人。谢谢!

答案 10 :(得分:-3)

不要使用NSApplication和NSApp ......

您只需指定实现UIApplicationDelegate协议的类:

UIApplicationMain(argc, argv, nil, @"Name of your class");