Playing with __attributes__ (二)

objc_boxable

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

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让开发者使用这个属性:ui

- (void)foo NS_REQUIRES_SUPER;

overloadable

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

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标准。不在此赘述。code

objc_runtime_name

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

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

objc_method_family

先来看一段代码:ip

@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有一些对于内存管理的命名规范。ci

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 连接

相关文章
相关标签/搜索