我正在编写一个需要很多参数的注册方法.最初,我为我的方法选择了以下方法.
// APPROACH #1
- (void)signUpWithInformation:(NSDictionary *)information
success:(void (^)(NSDictionary *))success
failure:(void (^)(NSError *))failure
{
// ...
NSDictionary *parameters = @{@"email": information[@"email"],
@"new_password": information[@"password"],
@"user_name": information[@"username"],
@"sex": ([information[@"sex"] isEqualToNumber:@(EFTUserSexMale)]) ? @"M" : @"F",
@"phone_nubmer": information[@"phoneNumber"],
@"weight": information[@"weight"],
@"height": information[@"height"],
@"birthday": [formatter stringFromDate:information[@"birthday"]]};
// ...
}
Run Code Online (Sandbox Code Playgroud)
但我觉得这种方法有些不适.虽然information给了我一些灵活性,但它需要装箱和拆箱来将值存储到字典中.
所以我想到了以下方法.
// APPROACH #2
- (void)signUpWithEmail:(NSString *)email
password:(NSString *)password
name:(NSString *)name
sex:(EFTUserSex)sex
phoneNumber:(NSString *)phoneNumber
weight:(double)weight
height:(double)height
birthday:(NSDate *)birthday
success:(void (^)(NSDictionary *))success
failure:(void (^)(NSError *))failure
{
// ...
NSDictionary *parameters = @{@"email": email,
@"new_password": password,
@"user_name": username,
@"sex": (sex == EFTUserSexMale) ? @"M" : @"F"
@"phone_nubmer": phoneNumber,
@"weight": weight,
@"height": height,
@"birthday": [formatter stringFromDate:birthday]};
// ...
}
Run Code Online (Sandbox Code Playgroud)
因为objective-c具有命名参数结构,我认为这种方法看起来像字典,并且不需要装箱和拆箱.
但是,我无法确定哪种方法最好.也许有另一种好方法?
更容易的是将所有这些数据抽象为自定义模型类.例如,您可以创建一个ETFUser类,该类具有与字典中所有键对应的属性.这是一个更好的面向对象设计(将类中的类似数据关联起来,而不是将数据作为参数或作为字典中的值关联),并且将为您提供编译时检查,即所有提供的值都是正确的类型,将所有内容放入字典时并非如此.使用字典还需要您记录要使用的所有正确的键和类型,但是在使用模型类时,很明显需要什么数据以及它应该是什么类型.
所以你会有一个带有这个接口的类EFTUser:
@interface ETFUser : NSObject
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *userName;
@property (nonatomic, strong) NSString *newPassword;
@property (nonatomic) EFTUserSex sex;
@property (nonatomic, strong) NSString *phoneNumber;
@property (nonatomic, strong) NSNumber *weight;
@property (nonatomic, strong) NSNumber *height;
@property (nonatomic, strong) NSDate *birthday;
@end
Run Code Online (Sandbox Code Playgroud)
现在,您可能仍需要生成此数据的字典版本,以便将身体参数传递给网络请求.在这种情况下,现在你有一个完美的地方来放置这些代码!- (NSDictionary *)dictionaryRepresentation向新EFTUser类添加一个方法,该方法将生成格式正确的字典以传递给网络请求.这可以防止在使用用户数据发出请求的任何位置复制代码.
您的示例中的方法现在可以简化为:
- (void)signUpWithUser:(EFTUser *)user
success:(void (^)(NSDictionary *))success
failure:(void (^)(NSError *))failure
{
NSDictionary *parameters = [user dictionaryRepresentation];
//...
}
Run Code Online (Sandbox Code Playgroud)