我正在编写一个iOS应用程序,该应用程序可向后兼容iOS 6.0。
在iOS 7中,NSString
实例方法drawInRect:withAttributes:
已取代drawInRect:withFont:lineBreakMode:alignment:
。要确定使用哪种方法,我有以下代码:
if ([NSString instancesRespondToSelector:@selector(drawInRect:withAttributes:)]) {
NSMutableParagraphStyle *textStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
[textStyle setLineBreakMode:NSLineBreakByTruncatingTail];
[textStyle setAlignment:NSTextAlignmentLeft];
[[self title] drawInRect:_textRect withAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:FONT_SIZE], NSParagraphStyleAttributeName: textStyle}];
}
else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[[self title] drawInRect:_textRect withFont:[UIFont boldSystemFontOfSize:FONT_SIZE] lineBreakMode:NSLineBreakByTruncatingTail alignment:NSTextAlignmentLeft];
#pragma clang diagnostic pop
}
由于iOS 7中引入了drawInRect:withAttributes:
,因此在早期版本的iOS上运行时,instancesRespondToSelector:
应返回false。但是,在运行iOS 6.1的设备上测试时,它返回true,然后在尝试调用drawInRect:withAttributes:
时崩溃。有谁知道发生了什么,或者我做错了什么?
答案 0 :(得分:4)
仅仅因为某个方法不是某个版本的公共API的一部分,并不意味着它不存在。我的猜测是-drawInRect:withAttributes:
是iOS 6中的私有API,然后在iOS 7中被提升为公共。您可以测试一些其他条件,您知道这些条件仅适用于iOS 6中的条件。例如if (NSClassFromString(@"SomeiOS7OnlyClass") != Nil)
。