MutableAttributedString适用于iOS 7但不适用于iOS 6

时间:2013-12-02 23:44:26

标签: ios objective-c ios6 ios7 nsattributedstring

我一直在使用从NSAttributedString文件创建.rtf的应用程序。我一直在iOS 7上测试这个应用没有问题。但是,当我在iOS 6上测试此应用程序时,我收到此错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteAttributedString initWithFileURL:options:documentAttributes:error:]: unrecognized selector sent to instance 0x9a77010'

这是我的代码:

NSError *error;
NSURL *stringURL = [[NSBundle mainBundle] URLForResource:@"Text" withExtension:@".rtf"];
NSAttributedString *myAttributedText = [[NSAttributedString alloc] initWithFileURL:stringURL options:nil documentAttributes:nil error:&error];

2 个答案:

答案 0 :(得分:4)

来自Apple文档 - NSAttributedString UIKit Additions Reference

initWithFileURL:options:documentAttributes:error:仅适用于iOS 7.0

编辑:正如评论中所述

如果要测试对象或协议(继承自NSObject)的选择器是否可用,那么在这种情况下可以使用[object respondsToSelector:@selector()]进行检查

NSAttributedString *myAttributedText;
if ([myAttributedText respondsToSelector:@selector(initWithFileURL:options:documentAttributes:error:)]) {
    myAttributedText = [[NSAttributedString alloc] initWithFileURL:stringURL options:nil documentAttributes:nil error:&error];
}
else {
    // Init some other way
}

答案 1 :(得分:0)

这种情况正在发生,因为你正在调用的方法

initWithFileURL:options:documentAttributes:error:

仅在iOS 7.0中引入。

您可以在此处查看iOS 6.1至iOS 7.0 API Diffs: iOS 6.1 to iOS 7.0 API Differences

在这里,具体来说,您可以看到NSAttributedString UIKit Additions Class Reference

调用不存在的方法会导致您的应用崩溃。您应该将部署目标设置为7.0或使用ifdefs之类的内容,以避免在早期版本(reference link here)中调用此方法。