Automatic Reference Counting
当 ARC 看到类似 copySomething 以 copy 开头的方法时,它将认为其返回值的引用计数增加了1。当调用与被调用的代码都在 ARC 的控制下,则无问题。但是当有一方不在 ARC 的控制时,则会出现泄露与崩溃。
NS_RETURNS_RETAINED, NS_RETURNS_NOT_RETAINED 可以用来修饰函数,解决上面的问题。
- No calls to retain, release, or autorelease
- No object pointers in C structs
- No casting between id and void* without a bridging cast
- No NSAutoreleasePool
Accessors
访问的优点:
- Key-value observing 依赖于访问器
- Side effects 访问器提供了赋值之外更多的操作。
- Locking 用于多线程访问的锁,在有访问器,代码更简洁,方便。
- Consistency 提供一致的访问方式。
不应该使用访问器的几个地方:
- Inside of accessors
- Dealloc
- Initialization
Categories and Extensions
编译期间并不检查 categories 中声明的函数是否实现。
不同的分类定义同名的函数,并无编译错误,运行时行为未定义。
+load 函数每个分类都可以实现,调用顺序不确定,但每个分类的 +load 函数确保只被调用一次。
Category Data Using Associative Reference
Category 不能定义 ivar ,Associative Reference 则可用来给任意对象添加 key-value 数据。
@interface Person : NSObject
@property (nonatomic, readwrite, copy) NSString *name;
@end
@implementation Person
@end
#import <objc/runtime.h>
@interface Person (EmailAddress)
@property (nonatomic, readwrite, copy) NSString *emailAddress;
@end
@implementation Person (EmailAddress)
static char emailAddressKey;
- (NSString *)emailAddress {
return objc_getAssociatedObject(self, &emailAddressKey);
}
- (void)setEmailAddress:(NSString *)emailAddress {
objc_setAssociatedObject(self, &emailAddressKey, OBJC_ASSOCIATION_COPY);
}
@end
Class Extensions
Extensions 中声明的函数在编译期间会被检查是否实现,其中可以定义 property 。