我有一个继承自 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/