objective-c - "unrecognized selector sent to instance"具有继承自 NSAttributedString 的类

标签 objective-c cocoa

我有一个继承自 NSAttributedString 的类,如下所示:

文本.h:

#import <Foundation/Foundation.h>

@interface Text : NSAttributedString

-(id) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing;

@end

文本.m:

#import "Text.h"

#import <Cocoa/Cocoa.h>

@implementation Text

-(id) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing
{
    NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setParagraphStyle: [NSParagraphStyle defaultParagraphStyle]];
    paragraphStyle.lineHeightMultiple = lineHeight;
    NSDictionary* attributes =
    @{
        NSFontAttributeName: font,
        NSKernAttributeName: @(letterSpacing),
        NSParagraphStyleAttributeName: paragraphStyle
    };
    self = [super initWithString:text attributes:attributes];
    return self;
}

@end

当我像这样实例化该类时:

[[Text alloc] initWithString:@"Test" andFont:welcomeLabelFont andLineHeight:52 andLetterSpacing:0.0f]];

我收到以下异常:

2017-07-17 17:21:15.771610+0300 Test[41403:10128169] -[Text initWithString:attributes:]: unrecognized selector sent to instance 0x600000000f70

选择器在基类中可用,事件 ctrl 单击它会跳转到 NSAttributedText 类。谁能指出我做错了什么吗?参数不是零指针,并且调用似乎是合法的。唯一看起来奇怪的是错误的类名是 Text 而不是 NSAttributedString

最佳答案

使用扩展来代替子类。像这样

// in NSAttributedString+init.h
//
@interface NSAttributedString (Init)

-(instancetype) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing;

@end

然后,`

// in NSAttributedString+init.m
//
#import "NSAttributedString+init.h"

@implementation NSAttributedString (Init)

-(instancetype) initWithString:(NSString*) text andFont:(NSFont*)font andLineHeight:(float) lineHeight andLetterSpacing:(float) letterSpacing {
    // ...
}

在您想要使用便捷初始化程序的任何地方导入该扩展 header 。

关于objective-c - "unrecognized selector sent to instance"具有继承自 NSAttributedString 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45146905/

相关文章:

javascript - 如何从 jQuery 代码中获取坐标值 (x,y) 并存储在 NSString 中?

iphone - 寻找用 Python 编写的适用于 iPhone 的 GUI 应用程序示例

objective-c - NSWindow 像警报面板一样阻止应用程序

ios - NSMutableArray 为每两个对象创建子数组,并在末尾注入(inject)一个空白字符串

ios - 在执行另一个方法时(动态地)更新标签文本

objective-c - Cocoa 为什么我必须保留和释放一个函数参数?

objective-c - 如何检测菜单栏应用程序中的鼠标位置?

objective-c - 如何在 NSImageView 中实现 NSImage 的连续旋转?

swift - 使用 NSTreeController 过滤 NSOutlineView 的子级

objective-c - 从主应用程序启动 Mac OS X (LoginItem) 助手应用程序