instacetype と typeof(self)

Presenter Notes

instancetype型

Presenter Notes

instancetypeの例

@interface A
+ (instancetype)constructAnA;
@end

は、以下と同じになる

@interface A
+ (A *)constructAnA;
@end

Presenter Notes

protocolでも

@protocol ConvenienceConstructor

+ (instancetype)defaultObject;

@end

@interface Clazz : NSObject <ConvenienceConstructor>

@end

Presenter Notes

instancetype継承

  • 継承した時に、 [ChildZ defaultObject]ChildZ *を返せる
@interface Clazz : NSObject
+ (instancetype)defaultObject;
@end

@interface ChildZ : Clazz
@end

Presenter Notes

自分自身のallloc

  • 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

Presenter Notes

typeof(self)

  • 自分自身のクラス型のweak selfを取得する例
__weak typeof(self) wself = self;
  • Blocksの循環参照対策に便利

Presenter Notes