Playing with __attributes__ (二)

发布时间:2019-08-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Playing with __attributes__ (二)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

objc_boxable

OC可能你经常会看到@(100)等用法。不用奇怪,就是这个Function attributes
使用示例:

struct __attribute__((objc_boxable)) some_struct {
  int i;
};
union __attribute__((objc_boxable)) some_union {
  int i;
  float f;
};
tyPEdef struct __attribute__((objc_boxable)) _some_struct some_struct;

some_struct ss;
NSValue *boxed = @(ss);

objc_requires_super

很多OC的class允许子类重载父类方法,但需要在重载的方法中调用父类方法。如:-[UIViewController viewDidLoad],-[UITableViewCell PRepareForReuse]等。 对于这样的情况,objc_requires_super就能派上用场。在父类的方法声明时使用该属性,能够使子类重载方法时必须调用父类方法。

- (void)foo __attribute__((objc_requires_super));

Foundation framework已经定义好了一个宏NS_REQUIRES_SUPER开发者使用这个属性:

- (void)foo NS_REQUIRES_SUPER;

overloadable

使C下的方法调用类似C++中的overload:

float __attribute__((overloadable)) tgsin(float x) { return sinf(x); }
double __attribute__((overloadable)) tgsin(double x) { return sin(x); }
long double __attribute__((overloadable)) tgsin(long double x) { return sinl(x); }

调用tgsin时会根据参数x类型决定调用对应的方法。具体参见C++99标准。不在此赘述。

objc_runtime_name

改变Class或者Protocol的运行时名称。
(水平有限,暂时不知道有何方便之处)

__attribute__((objc_runtime_name("MyLocalName")))
@interface Message
@end

objc_method_family

先来看一段代码:

@interface MyObject: NSObject
@property (nonatomic) newValue;
@end

编译出现error如下:
Property follows Cocoa naming convention for returning 'owned' objects
Explicitly declare getter '-newValue' with '__attribute__((objc_method_family(none)))' to return an 'unowned' object

在支持ARC后,clang有一些对于内存管理的命名规范。

You take ownership of an object if you create it using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”

所以,如果方法名alloc, new, copy, mutableCopy开头的函数都会被作为生成新对象的函数对返回对象retainCount自增1.
解决办法为,在Property后加入 __attribute__((objc_method_family(none)))

其他用法:

__attribute__((objc_method_family(X)))

X可以是none, alloc, copy, init, mutableCopy, new其中之一。放在property或者函数后面。

当然你也可以使不满足编译器命名规则的方法成为生成新对象的方法,如:

- (id) createObject __attribute__((objc_method_family(new)));

下期会介绍剩下的和一些有用的宏

原作写于segmentfault 链接

脚本宝典总结

以上是脚本宝典为你收集整理的Playing with __attributes__ (二)全部内容,希望文章能够帮你解决Playing with __attributes__ (二)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。