🚩 | 问题
风格纠错
📌 | 解答
typedef enum{
UserSex_Man,
UserSex_Woman
}UserSex;
@interface UserModel :NSObject
@property(nonatomic, strong) NSString *name;
@property (assign, nonatomic) int age;
@property (nonatomic, assign) UserSex sex;
-(id)initUserModelWithUserName: (NSString*)name withAge:(int)age;
-(void)doLogin;
@end
题解:
typedef NS_ENUM(NSUInteger, JXSex) {
JXSexMan,
JXSexWoman
};
@interface UserModel : NSObject
@property (nonatomic, readonly, copy) NSString *name;
@property (nonatomic, readonly, assign) NSUInteger age;
@property (nonatomic, readonly, assign) JXSex sex;
- (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(JXSex)sex;
+ (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(JXSex)sex;
@end
优化部分:
1.enum 建议使用 NS\_ENUM 和 NS\_OPTIONS 宏来定义枚举类型。题目中,只有男性和女性,不够严谨,最好有个保密。
2.age 属性的类型,这里我们应该避免使用基本类型(这样做是基于64-bit考虑),同时考虑到 age 的特点,需要的类型就更需要注意。
3.如果工程项目很大,需要拆分成不同的模块,可以在类、typedef宏命名的时候使用前缀。
4.doLogin方法不应写在该类中。登录操作属于业务逻辑,业务逻辑不应该出现在模型中,应该在 MVC 中的 C 中,或者 MVVM 的 VM 中。
5.doLogin命名不规范。
6.-\(id\)initUserModelWithUserName: \(NSString\*\)name withAge:\(int\)age;方法中不要使用with来连接两个参数。使用and连接的应该是两个独立的操作。返回值类型不建议使用 id 类型。
7.由于字符串值可能会改变,这里建议使用 相关属性的 内存管理语义 声明为 copy
8.初始化方法中只有 name 和 age 那么 sex 无法初始化。
#import "UserModel.h"
@implementation UserModel
- (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(JXSex)sex {
if (self = [super init]) {
_name = [name copy];
_age = age;
_sex = sex;
}
return self;
}
+ (instancetype)initWithName:(NSString *)name age:(NSUInteger)age sex:(JXSex)sex {
return [self initWithName:name age:age sex:sex];
}
@end
9.initUserModelWithUserName 如果改成 initWithName 会更加简洁清晰。
10.@property \(assign, nonatomic\) int age; 顺序不合理 应该是 @property \(nonatomic, readonly, copy\) NSString \*name;
必须要改:
1.在 - 和 \(void\)之间应该有一个空格。
2.enum 中的命名规则驼峰和下划线混用,应使用驼峰法。
3.enum 左括号前加空格或者换行。
4.enum 右括号后加一个空格。
5.@interface UserModel :NSObject 应改为 @interface UserModel : NSObject。少一个空格。
6.两个方法定义之间不需要换行,有时候为了区分方法的功能是可以换一行的。
7.@interface 和 @property 属性声明中间应该隔一行。
8.-\(id\)initUserModelWithUserName: \(NSString\*\)name withAge:\(int\)age;中-\(id\)没有空格。
9.-\(id\)initUserModelWithUserName: \(NSString\*\)name withAge:\(int\)age;中\(NSString\*\)name前多了空格。
10.-\(id\)initUserModelWithUserName: \(NSString\*\)name withAge:\(int\)age;中\(NSString\*\)name中\(NSString \*\)name少空格。