id型の代わりにメソッドの返り値に指定するメソッドの返り値以外の場所では使用できない
@interface A
+ (instancetype)constructAnA;
@end
は、以下と同じになる
@interface A
+ (A *)constructAnA;
@end
@protocol ConvenienceConstructor
+ (instancetype)defaultObject;
@end
@interface Clazz : NSObject <ConvenienceConstructor>
@end
[ChildZ defaultObject] が ChildZ *を返せる@interface Clazz : NSObject
+ (instancetype)defaultObject;
@end
@interface ChildZ : Clazz
@end
KnowledgeModel クラスBad :
+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict
{
id instance = [[Knowledge alloc] initWithDictionary:dict];
return instance;
}
Good :
+ (instancetype)modelObjectWithDictionary:(NSDictionary *)dict
{
id instance = [[[self class] alloc] initWithDictionary:dict];
return instance;
}
Example code from JSON Accelerator
__weak typeof(self) wself = self;
| instacetype と typeof(self) | 1 |
|---|---|
| instancetype型 | 2 |
| instancetypeの例 | 3 |
| protocolでも | 4 |
| instancetype継承 | 5 |
| 自分自身のallloc | 6 |
| typeof(self) | 7 |
| Table of Contents | t |
|---|---|
| Exposé | ESC |
| Full screen slides | e |
| Presenter View | p |
| Source Files | s |
| Slide Numbers | n |
| Toggle screen blanking | b |
| Show/hide slide context | c |
| Notes | 2 |
| Help | h |