在Cocoa命令行程序中运行NSRunLoop

时间:2010-01-28 12:57:02

标签: objective-c cocoa

是否可以在不加载任何NIB文件的情况下初始化NSRunLoop(即,不调用NSApplicationMain())?

感谢。

6 个答案:

答案 0 :(得分:15)

解决方案是手动调用NSApplication。首先创建您的应用程序委托,而不是使用以下内容替换main.m中的NSApplicationMain()调用:

AppDelegate * delegate = [[AppDelegate alloc] init];

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSApplication * application = [NSApplication sharedApplication];
[application setDelegate:delegate];
[NSApp run];

[pool drain];

[delegate release];

准备就绪时将调用委托,而不需要笔尖

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification

答案 1 :(得分:14)

在Swift中,您可以通过将以下行添加到main.swift的末尾来实现此目的:

NSRunLoop.currentRunLoop().run();  // Swift < 3.0
RunLoop.current.run();             // Swift >= 3.0

如果您希望能够停止运行循环,则必须使用Core Foundation方法。

CFRunLoopRun(); // start

你可以像这样停止它

CFRunLoopStop(CFRunLoopGetCurrent()); // stop

答案 2 :(得分:11)

是;您可以编写自己的主方法并运行NSRunLoop,而无需从NSApplicationMain返回。

看看这个link;这家伙在他的主要方法中使用NSRunLoop,虽然他没有加载NIB文件,但它应该让你使用NSRunloops

答案 3 :(得分:8)

// Yes.  Here is sample code (tested on OS X 10.8.4, command-line).
// Using ARC:
// $ cc -o timer timer.m -fobjc-arc -framework Foundation
// $ ./timer
//

#include <Foundation/Foundation.h>

@interface MyClass : NSObject
@property NSTimer *timer;
-(id)init;
-(void)onTick:(NSTimer *)aTimer;
@end

@implementation MyClass
-(id)init {
    id newInstance = [super init];
    if (newInstance) {
        NSLog(@"Creating timer...");
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0
            target:self
            selector:@selector(onTick:)
            userInfo:nil
            repeats:YES];
    }
    return newInstance;
}

-(void)onTick:(NSTimer *)aTimer {
    NSLog(@"Tick");
}
@end

int main() {
    @autoreleasepool {
        MyClass *obj = [[MyClass alloc] init];
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

答案 4 :(得分:6)

遵循[NSRunLoop run]文档中的建议:

BOOL shouldKeepRunning = YES;        // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate     distantFuture]]);

答案 5 :(得分:5)

查看手动运行NSRunLoop的asynctask.m 启用异步“waitForDataInBackgroundAndNotify”通知。

http://www.cocoadev.com/index.pl?NSPipe

  NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

   while(!terminated) 
   {
     //if (![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:100000]])
     if (![[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) 
     {
         break;
     }
      [pool release];
      pool = [[NSAutoreleasePool alloc] init];
   }

   [pool release];