我目前正在为 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
@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
但是,通过该方法返回一个空对象init
让我有点困扰,我问自己这是否是一个好主意,但我不知道为什么它可能会有风险。
所以我问你:我可以使用这个结构吗?如果不是,为什么?我应该以经典方式使用与init
方法耦合的单个loadWithUsername:(NSString *)username success:(void (^)(JPImgurAccount *))success failure:(void (^)(NSError *))failure
方法吗?
谢谢。