我有一个继承自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
类。任何人都可以指出我做错了什么?参数不是零指针,调用似乎是合法的。唯一看起来很奇怪的是错误的类名Text
而不是NSAttributedString
。
答案 0 :(得分:4)
子类的Instad,使用扩展名。喜欢这个
// 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 {
// ...
}
在您想要使用便利初始化程序的任何地方导入该扩展程序标题。