Objective-C中的异步初始化

Nes*_*esk 3 asynchronous initialization objective-c

我目前正在为API创建一个Objective-C库.为了轻松管理数据,我创建了一些充当模型的类.

例如,我有一个Account类,其中包含有关一个特定帐户的所有数据.我希望能够轻松地创建这个类,我想到了这样的事情:

@interface Account : NSObject

@property (nonatomic, readonly) NSUInteger accountID;
@property (nonatomic, readonly) NSString *username;

// Other properties...

+ (instancetype)accountWithUsername:(NSString *)username success:(void (^)(Account *))success failure:(void (^)(NSError *))failure;
- (instancetype)initWithUsername:(NSString *)username success:(void (^)(Account *))success failure:(void (^)(NSError *))failure;

@end
Run Code Online (Sandbox Code Playgroud)

 

@implementation Account

+ (instancetype)accountWithUsername:(NSString *)username success:(void (^)(Account *))success failure:(void (^)(NSError *))failure
{
    return [[JPImgurAccount alloc] initWithUsername:username success:success failure:failure];
}

- (instancetype)initWithUsername:(NSString *)username success:(void (^)(Account *))success failure:(void (^)(NSError *))failure
{
    self = [super init];

    // Launch asynchronous requests, the callback will be called when it's finished

    return self; // Returning an empty object until the asynchronous request is finished
}

@end
Run Code Online (Sandbox Code Playgroud)

然而,通过这个init方法返回一个空对象让我感到困扰,我问自己这是不是一个好主意,但我无法找到它为什么会有风险.

所以我问你:我可以使用这种结构吗?如果没有,为什么?我应该采用经典方式使用init耦合到loadWithUsername:(NSString *)username success:(void (^)(JPImgurAccount *))success failure:(void (^)(NSError *))failure方法的单一方法吗?

谢谢.

Eli*_*nem 5

我不认为你的方法是好的做法.作为API的用户,当我看到以"init"开头的方法时,我希望返回的对象可以立即使用.看起来您需要使用Factory设计模式.使用此方法创建AccountFactory类:

+ (void)createAccountWithUsername:(NSString*)username success:(void (^)(Account *))success failure:(void (^)(NSError *))failure;
Run Code Online (Sandbox Code Playgroud)

请注意,它返回void,因此用户了解该对象仅在请求成功完成后才可用.此外,用户理解他不希望直接创建帐户实例.这就是我要用的方法.