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

Text.h:

#import <Foundation/Foundation.h>

@interface Text : NSAttributedString

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

@end


Text.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类。谁能指出我做错了什么?参数不是nil指针,并且该调用似乎合法。唯一看起来很奇怪的是该错误的类名称为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 {
    // ...
}

将该扩展头导入到要使用便捷初始化程序的任何位置。

关于objective-c - 带有从NSAttributedString继承的类的“无法识别的选择器发送到实例”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45146905/

10-15 10:30