objective-c - 为什么我的目标没有打印到控制台?

标签 objective-c cocoa

我刚刚开始学习目标,并按照所有说明创建了我的第一个控制台应用程序,该应用程序应该打印“哎呀!”每两秒一次,但尽管它在循环,但它没有打印到控制台,我不明白为什么。有人介意告诉我我做错了什么吗?

我的 .h 文件具有以下内容:

#import <Foundation/Foundation.h>

@interface Logger : NSObject

- (void)sayOuch:(NSTimer *)t;

@end

我的 .m 文件具有以下内容:

#import "Logger.h"

@implementation Logger


- (void)sayOuch:(NSTimer *)t
{
    NSLog(@"Ouch!");
}


@end

最后,我的 main.m 文件包含以下内容:

#import <Foundation/Foundation.h>
#import "Logger.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {


        Logger *logger = [[Logger alloc] init];
        __unused NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 
                                                 target:logger 
                                               selector:@selector(sayOuch:) 
                                               userInfo:nil 
                                                repeats:YES];
        [[NSRunLoop currentRunLoop] run];

    }
    return 0;
}

问题是,每当我运行消息“哎呀!”时没有打印到我的控制台。感谢您提前提供的帮助。

最佳答案

改变

timerWithTimeInterval

scheduledTimerWithTimeInterval

所以你的代码更改为工作:

#import <Foundation/Foundation.h>
#import "Logger.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {


        Logger *logger = [[Logger alloc] init];
        __unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 
                                                                   target:logger 
                                                                 selector:@selector(sayOuch:) 
                                                                 userInfo:nil 
                                                                  repeats:YES];

        [[NSRunLoop currentRunLoop] run];

    }
    return 0;
}

关于objective-c - 为什么我的目标没有打印到控制台?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035258/

相关文章:

ios - 用户定义的运行时属性和关联对象

ios - 防止 UITableViewCells 重复内容

objective-c - 在 iOS 中使用 Twitter 登录用户...使用什么?

objective-c - 如何在运行时在 Objective-C 中创建协议(protocol)?

objective-c - 如何以编程方式从 View 层次结构中的另一个 subview 引用 subview ?

iphone - 使用 NSArray 填充 UITableView 行 0 静态和其余部分

编译从书中逐字复制的代码会导致编译器错误

cocoa - 防止沙盒应用程序中出现 Cmd+Shift+Q 警报

objective-c - 概述系统窗口

objective-c - 对类实例的全局访问 - 最佳设计方法?