我可以在Objective-C中为自己的弃用添加fix-it吗?

rai*_*lin 2 objective-c deprecated ios

试图找出我是否可以为自己的弃用创建自己的"修复"建议?有可能吗?如果是,那么任何资源都将非常感激!

rob*_*off 6

您可以使用以下deprecated属性:

@interface MyObject: NSObject
- (void)oldMethod
    __attribute__((deprecated("Don't use this", "newMethod")))
    ;
- (void)newMethod;
@end
Run Code Online (Sandbox Code Playgroud)

如果要从特定操作系统版本弃用,可以使用clang的availability属性.请注意,您只能基于操作系统版本而不是您自己的库版本弃用.

例:

#import <Foundation/Foundation.h>

@interface MyObject: NSObject
- (void)oldMethod
    __attribute__((availability(ios,deprecated=12.0,replacement="newMethod")))
    ;
- (void)newMethod;
@end

@implementation MyObject

- (void)oldMethod { }
- (void)newMethod { }

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        MyObject *o = [[MyObject alloc] init];
        [o oldMethod]; // Xcode offers a fix-it to use newMethod instead.
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果需要,可以使用API_DEPRECATED_WITH_REPLACEMENT定义的宏<os/availability.h>而不是直接使用clang属性.该头文件中有注释说明其用法.