如何弃用Xcode中的方法

时间:2011-02-07 17:18:22

标签: objective-c xcode cocoa cocoa-touch deprecated

我们将我们的库发送给客户,并且我想将某些方法标记为“已弃用”,因为我们更改了它们(就像Apple在iPhone SDK中所做的那样)。

我见过__OSX_AVAILABLE_BUT_DEPRECATED预处理器宏,它映射到__AVAILABILITY_INTERNAL,映射到__attribute__((deprecated)) ...

我对这些东西感到有些困惑!

有人知道这件事吗?

5 个答案:

答案 0 :(得分:148)

__attribute__((deprecated))是将函数/方法标记为已弃用的gcc way(也是supported in clang)。当一个被标记为“已弃用”时,每当有人调用它时都会产生警告。

普通函数的语法是

__attribute__((deprecated))
void f(...) {
  ...
}

// gcc 4.5+ / clang
__attribute__((deprecated("g has been deprecated please use g2 instead")))
void g(...) {
  ...
}

和Objective-C方法的那些

@interface MyClass : NSObject { ... }
-(void)f:(id)x __attribute__((deprecated));
...
@end

您还可以使用

将整个班级标记为已弃用
__attribute__((deprecated))
@interface DeprecatedClass : NSObject { ... }
...
@end

Apple还提供了<AvailabilityMacros.h>标头,它提供了扩展到上述属性的DEPRECATED_ATTRIBUTE和DEPRECATED_MSG_ATTRIBUTE(msg)宏,如果编译器不支持属性,则不提供任何内容。请注意,此标头在OS X / iOS之外不存在。


旁注,如果您使用Swift,则使用@available attribute弃用某个项目,例如

@available(*, deprecated=2.0, message="no longer needed")
func f() {
    ...
}

答案 1 :(得分:70)

您还可以使用更具可读性的定义 DEPRECATED_ATTRIBUTE

它在usr/include/AvailabilityMacros.h中定义:

#define DEPRECATED_ATTRIBUTE        __attribute__((deprecated))
#define DEPRECATED_MSG_ATTRIBUTE(msg) __attribute((deprecated((msg))))

Objective-C 方法示例:

@interface MyClass : NSObject { ... }
-(void)foo:(id)x DEPRECATED_ATTRIBUTE;

// If you want to specify deprecated message:
-(void)bar:(id)x DEPRECATED_MSG_ATTRIBUTE("Use baz: method instead.");
...
@end

您还可以将整个班级标记为已弃用:

DEPRECATED_ATTRIBUTE
@interface DeprecatedClass : NSObject { ... }
...
@end

答案 2 :(得分:1)

如果您在xcode项目中使用C ++ 14,则还可以使用现在属于该语言的[[deprecated]][[deprecated("reason")]]属性。

请参阅文档:http://en.cppreference.com/w/cpp/language/attributes

答案 3 :(得分:0)

-用于SWIFT代码:

将此放在方法上方: @available(*, deprecated: <#Version#>, message: <#Message#>)

示例:

@available(*, deprecated: 11, message: "Use color assets instead")
public struct ColorPaletteItemResource: ColorPaletteItemResourceType {
    ...
}

答案 4 :(得分:0)

Swift 5.0

使用@available弃用任何方法/类/结构/协议

@available(*, deprecated, message: "Parse your data by hand instead")
func parseData() { }

@available(*, deprecated, renamed: "loadData")
func fetchData() { }

@available(swift, obsoleted: 4.1, renamed: "attemptConnection")
func testConnection() { }

@available(swift, deprecated: 4.0, obsoleted: 5.0, message: "This will be removed in v5.0; please migrate to a different API.")

可能的参数:

  • 介绍了
  • 已弃用
  • 已过时
  • 消息
  • 重命名

有关更多信息,请参阅Apple文档:Attributes