技术标签: iOS代码规范 Swift学习笔记 编程语言规范 iOS开发技术分享 swift代码规范 iOS开发实战 韩俊强的博客 oc代码
这篇规范一共分为三个部分:
因为软件是需要人来维护的。这个人在未来很可能不是你。所以首先是为人编写程序,其次才是计算机:
需求是暂时的,只有变化才是永恒的。
本次迭代不能仅仅为了当前的需求,写出扩展性强,易修改的程序才是负责任的做法,对自己负责,对公司负责。
过度工程(over-engineering):在正确可用的代码写出之前就过度地考虑扩展,重用的问题,使得工程过度复杂。
- 先把眼前的问题解决掉,解决好,再考虑将来的扩展问题。
- 先写出可用的代码,反复推敲,再考虑是否需要重用的问题。
- 先写出可用,简单,明显没有bug的代码,再考虑测试的问题。
推荐这样写:
white(someCondition){
}
//函数
void function(param1,param2)
{
}
!bValue
~iValue
++iCount
*strSource
&fSum
fWidth = 5 + 5;
fLength = fWidth * 2;
fHeight = fWidth + fLength;
for(int i = 0; i < 10; i++)
在多个不同的运算符同时存在的时候应该合理使用括号,不要盲目依赖操作符优先级。
因为有的时候不能保证阅读你代码的人就一定能了解你写的算式里面所有操作符的优先级。
来看一下这个算式:2 << 2 + 1 * 3 - 4
这里的<<
是移位操作直观上却很容易认为它的优先级很高,所以就把这个算式误认为:(2 << 2) + 1 _ 3 - 4
但事实上,它的优先级是比加减法还要低的,所以该算式应该等同于:2 << (2 + 1 _ 3 - 4)。
所以在以后写这种复杂一点的算式的时候,尽量多加一点括号,避免让其他人误解(甚至是自己)。
推荐这样写:
func someFunction() {
let index = ...;
//Do something With index
...
...
let count = ...;
//Do something With count
}
不推荐这样写:
func someFunction() {
let index = ...;
let count = ...;
//Do something With index
...
...
//Do something With count
}
推荐这样写:
var hintStr;
if (count < 3) {
hintStr = "Good";
} else {
hintStr = "";
}
不推荐这样写:
var hintStr;
if (count < 3) {
hintStr = "Good";
}
推荐这样写:
- (void)someMethod {
if (!goodCondition) {
return;
}
//Do something
}
不推荐这样写:
- (void)someMethod {
if (goodCondition) {
//Do something
}
}
比较典型的例子我在JSONModel里遇到过:
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError)err
{
//方法1. 参数为nil
if (!dict) {
if (err) *err = [JSONModelError errorInputIsNil];
return nil;
}
//方法2. 参数不是nil,但也不是字典
if (![dict isKindOfClass:[NSDictionary class]]) {
if (err) *err = [JSONModelError errorInvalidDataWithMessage:@"Attempt to initialize JSONModel object using initWithDictionary:error: but the dictionary parameter was not an 'NSDictionary'."];
return nil;
}
//方法3. 初始化
self = [self init];
if (!self) {
//初始化失败
if (err) *err = [JSONModelError errorModelIsInvalid];
return nil;
}
//方法4. 检查用户定义的模型里的属性集合是否大于传入的字典里的key集合(如果大于,则返回NO)
if (![self __doesDictionary:dict matchModelWithKeyMapper:self.__keyMapper error:err]) {
return nil;
}
//方法5. 核心方法:字典的key与模型的属性的映射
if (![self __importDictionary:dict withKeyMapper:self.__keyMapper validation:YES error:err]) {
return nil;
}
//方法6. 可以重写[self validate:err]方法并返回NO,让用户自定义错误并阻拦model的返回
if (![self validate:err]) {
return nil;
}
//方法7. 终于通过了!成功返回model
return self;
}
可以看到,在这里,首先判断出各种错误的情况然后提前返回,把最正确的情况放到最后返回。
推荐这样写:
let nameContainsSwift = sessionName.hasPrefix("Swift")
let isCurrentYear = sessionDateCompontents.year == 2014
let isSwiftSession = nameContainsSwift && isCurrentYear
if (isSwiftSession) {
// Do something
}
不推荐这样写:
if ( sessionName.hasPrefix("Swift") && (sessionDateCompontents.year == 2014) ) {
// Do something
}
推荐这样写:
if ( count == 6) {
}
或者
if ( object == nil) {
}
或者
if ( !object ) {
}
不推荐这样写:
if ( 6 == count) {
}
或者
if ( nil == object ) {
}
推荐这样写:
if (!error) {
return success;
}
不推荐这样写:
if (!error)
return success;
或者
if (!error) return success;
推荐这样写:
if (condition1() &&
condition2() &&
condition3() &&
condition4()) {
// Do something
}
不推荐这样写:
if (condition1() && condition2() && condition3() && condition4()) {
// Do something
}
for (int index = 0; index < 10; index++){
...
logicToChange(index)
}
continue和break所描述的是“什么时候不做什么”,所以为了读懂二者所在的代码,我们需要在头脑里将他们取反。
其实最好不要让这两个东西出现,因为我们的代码只要体现出“什么时候做什么”就好了,而且通过适当的方法,是可以将这两个东西消灭掉的:
var filteredProducts = Array<String>()
for level in products {
if level.hasPrefix("bad") {
continue
}
filteredProducts.append(level)
}
我们可以看到,通过判断字符串里是否含有“bad”这个prefix来过滤掉一些值。其实我们是可以通过取反,来避免使用continue的:
for level in products {
if !level.hasPrefix("bad") {
filteredProducts.append(level)
}
}
在while里的block其实就相当于“不存在”,既然是不存在的东西就完全可以在最开始的条件语句中将其排除。
while里的break:
while (condition1) {
...
if (condition2) {
break;
}
}
取反并合并到主条件:
while (condition1 && !condition2) {
...
}
有些朋友喜欢这样做:在有返回值的方法里break之后,再返回某个值。其实完全可以在break的那一行直接返回。
func hasBadProductIn(products: Array<String>) -> Bool {
var result = false
for level in products {
if level.hasPrefix("bad") {
result = true
}
}
return result
}
遇到错误条件直接返回:
func hasBadProductIn(products: Array<String>) -> Bool {
for level in products {
if level.hasPrefix("bad") {
return true
}
}
return false
}
这样写的话不用特意声明一个变量来特意保存需要返回的值,看起来非常简洁,可读性高。
推荐这样写:
switch (integer) {
case 1: {
// ...
}
break;
case 2: {
// ...
break;
}
case 3: {
// ...
break;
}
default:{
// ...
break;
}
}
RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain;
switch (menuType) {
case RWTLeftMenuTopItemMain: {
// ...
break;
}
case RWTLeftMenuTopItemShows: {
// ...
break;
}
case RWTLeftMenuTopItemSchedule: {
// ...
break;
}
}
在Switch语句使用枚举类型的时候,如果使用了default分支,在将来就无法通过编译器来检查新增的枚举类型了。
通常来说,在阅读一个函数的时候,如果视需要跨过很长的垂直距离会非常影响代码的阅读体验。如果需要来回滚动眼球或代码才能看全一个方法,就会很影响思维的连贯性,对阅读代码的速度造成比较大的影响。最好的情况是在不滚动眼球或代码的情况下一眼就能将该方法的全部代码映入眼帘。
每个函数的职责都应该划分的很明确(就像类一样)。
推荐这样写:
dataConfiguration()
viewConfiguration()
不推荐这样写:
void dataConfiguration()
{
...
viewConfiguration()
}
推荐这样写:
int function()
{
if(condition1){
return count1
}else if(condition2){
return count2
}else{
return defaultCount
}
}
不推荐这样写:
int function()
{
if(condition1){
return count1
}else if(condition2){
return count2
}
}
推荐这样写:
void function(param1,param2)
{
if(param1 is unavailable){
return;
}
if(param2 is unavailable){
return;
}
//Do some right thing
}
原来的调用:
void logic() {
a();
b();
if (logic1 condition) {
c();
} else {
d();
}
}
将a,b函数抽取出来作为单独的函数
void basicConfig() {
a();
b();
}
void logic1() {
basicConfig();
c();
}
void logic2() {
basicConfig();
d();
}
一个函数内的不清晰(逻辑判断比较多,行数较多)的那片代码,往往可以被提取出去,构成一个新的函数,然后在原来的地方调用它这样你就可以使用有意义的函数名来代替注释,增加程序的可读性。
举一个发送邮件的例子:
openEmailSite();
login();
writeTitle(title);
writeContent(content);
writeReceiver(receiver);
addAttachment(attachment);
send();
中间的部分稍微长一些,我们可以将它们提取出来:
void writeEmail(title, content,receiver,attachment)
{
writeTitle(title);
writeContent(content);
writeReceiver(receiver);
addAttachment(attachment);
}
然后再看一下原来的代码:
openEmailSite();
login();
writeEmail(title, content,receiver,attachment)
send();
在一个类里面,经常会有传递某些变量的情况。而如果需要传递的变量是某个全局变量或者属性的时候,有些朋友不喜欢将它们作为参数,而是在方法内部就直接访问了:
class A {
var x;
func updateX() {
...
x = ...;
}
func printX() {
updateX();
print(x);
}
}
我们可以看到,在printX方法里面,updateX和print方法之间并没有值的传递,乍一看我们可能不知道x从哪里来的,导致程序的可读性降低了。
而如果你使用局部变量而不是类成员来传递信息,那么这两个函数就不需要依赖于某一个类,而且更加容易理解,不易出错:
func updateX() -> String{
x = ...;
return x;
}
func printX() {
String x = updateX();
print(x);
}
优秀的代码大部分是可以自描述的,我们完全可以用程代码本身来表达它到底在干什么,而不需要注释的辅助。
但并不是说一定不能写注释,有以下三种情况比较适合写注释:
除了上述这三种情况,如果别人只能依靠注释才能读懂你的代码的时候,就要反思代码出现了什么问题。
最后,对于注释的内容,相对于“做了什么”,更应该说明“为什么这么做”。
换行、注释、方法长度、代码重复等这些是通过机器检查出来的问题,是无需通过人来做的。
而且除了审查需求的实现的程度,bug是否无处藏身以外,更应该关注代码的设计。比如类与类之间的耦合程度,设计的可扩展性,复用性,是否可以将某些方法抽出来作为接口等等。
类,协议使用大驼峰:
HomePageViewController.h
<HeaderViewDelegate>
对象等局部变量使用小驼峰:
NSString *personName = @"";
NSUInteger totalCount = 0;
UIButton *addBtn //添加按钮
UILabel *nameLbl //名字标签
NSString *addressStr//地址字符串
类型 | 后缀 |
---|---|
UIViewController | VC |
UIView | View |
UILabel | Lbl |
UIButton | Btn |
UIImage | Img |
UIImageView | ImagView |
NSArray | Array |
NSMutableArray | Marray |
NSDictionary | Dict |
NSMutableDictionary | Mdict |
NSString | Str |
NSMutableString | MStr |
NSSet | Set |
NSMutableSet | Mset |
推荐这样写:
static const NSTimeInterval ZOCSignInViewControllerFadeOutAnimationDuration = 0.4;
不推荐这样写:
static const NSTimeInterval fadeOutTime = 0.4;
首先比较一下这两种声明常量的区别:
使用预处理虽然能达到替换文本的目的,但是本身还是有局限性的:
如果我们需要发送通知,那么就需要在不同的地方拿到通知的“频道”字符串(通知的名称),那么显然这个字符串是不能被轻易更改,而且可以在不同的地方获取。这个时候就需要定义一个外界可见的字符串常量。
推荐这样写:
//头文件
extern NSString *const ZOCCacheControllerDidClearCacheNotification;
不推荐这样写:
#define CompanyName @"Apple Inc."
#define magicNumber 42
#define URL_GAIN_QUOTE_LIST @"/v1/quote/list"
#define URL_UPDATE_QUOTE_LIST @"/v1/quote/update"
#define URL_LOGIN @"/v1/user/login”
#define MY_MIN(A, B) ((A)>(B)?(B):(A))
其实iOS内部已经提供了相应的获取CGRect各个部分的函数了,它们的可读性比较高,而且简短,推荐使用:
推荐这样写:
CGRect frame = self.view.frame;
CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
CGRect frame = CGRectMake(0.0, 0.0, width, height);
而不是
CGRect frame = self.view.frame;
CGFloat x = frame.origin.x;
CGFloat y = frame.origin.y;
CGFloat width = frame.size.width;
CGFloat height = frame.size.height;
CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size };
建议在定义NSArray和NSDictionary时使用泛型,可以保证程序的安全性:
NSArray<NSString *> *testArr = [NSArray arrayWithObjects:@"Hello", @"world", nil];
NSDictionary<NSString *, NSNumber *> *dic = @{@"key":@(1), @"age":@(10)};
为常用的Block类型创建typedef
如果我们需要重复创建某种block(相同参数,返回值)的变量,我们就可以通过typedef来给某一种块定义属于它自己的新类型
例如:
int (^variableName)(BOOL flag, int value) =^(BOOL flag, int value){
// Implementation
return someInt;
}
这个Block有一个bool参数和一个int参数,并返回int类型。我们可以给它定义类型:
int(^EOCSomeBlock)(BOOL flag, int value);
再次定义的时候,就可以通过简单的赋值来实现:
EOCSomeBlock block = ^(BOOL flag, int value){
// Implementation
};
定义作为参数的Block:
(void)startWithCompletionHandler: (void(^)(NSData _data, NSError _error))completion;
这里的Block有一个NSData参数,一个NSError参数并没有返回值
typedef void(^EOCCompletionHandler)(NSData _data, NSError _error);
-(void)startWithCompletionHandler:(EOCCompletionHandler)completion;
通过typedef定义Block签名的好处是:如果要某种块增加参数,那么只修改定义签名的那行代码即可。
尽量使用字面量值来创建 NSString , NSDictionary , NSArray , NSNumber 这些不可变对象:
推荐这样写
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
NSNumber *shouldUseLiterals = @YES;NSNumber *buildingZIPCode = @10018;
不推荐这样写:
NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill" ];
NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];NSNumber *buildingZIPCode = [NSNumber numberWithInteger:10018];
推荐这样写:
@property (nonatomic, readwrite, strong) UIButton *confirmButton;
推荐这样写:
@property (nonatomic, readwrite, copy) NSString *name;
@property (nonatomic, readonly, copy) NSString *gender;
@property (nonatomic, readwrite, strong) UIView *headerView;
推荐这样写:
typedef void (^ErrorCodeBlock) (id errorCode,NSString *message);
@property (nonatomic, readwrite, copy) ErrorCodeBlock errorBlock;//将block拷贝到堆中
推荐这样写:
@property (assign, getter=isEditable) BOOL editable;
实例化一个对象是需要耗费资源的,如果这个对象里的某个属性的实例化要调用很多配置和计算,就需要懒加载它,在使用它的前一刻对它进行实例化:
- (NSDateFormatter *)dateFormatter {
if (!_dateFormatter) {
_dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[_dateFormatter setLocale:enUSPOSIXLocale];
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
}
return _dateFormatter;
}
但是也有对这种做法的争议:getter方法可能会产生某些副作用,例如如果它修改了全局变量,可能会产生难以排查的错误。
使用点语法的好处:
注意:
1. 懒加载的属性,必须通过点语法来读取数据。因为懒加载是通过重写getter方法来初始化实例变量的,如果不通过属性来读取该实例变量,那么这个实例变量就永远不会被初始化。
2. 在init和dealloc方法里面使用点语法的后果是:因为没有绕过setter和getter,在setter和getter里面可能会有很多其他的操作。而且如果它的子类重载了它的setter和getter方法,那么就可能导致该子类调用其他的方法。
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
不推荐这样写:
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
readwrite
。这样一来,在外部就只能读取该数据,而不能修改它,使得这个类的实例所持有的数据更加安全。而且,对于集合类的对象,更应该仔细考虑是否可以将其设为可变的。如果在公开部分只能设置其为只读属性,那么就在非公开部分存储一个可变型。所以当在外部获取这个属性时,获取的只是内部可变型的一个不可变版本,例如: @interface EOCPerson : NSObject
@property (nonatomic, copy, readonly) NSString _firstName;
@property (nonatomic, copy, readonly) NSString _lastName;
@property (nonatomic, strong, readonly) NSSet *friends //向外公开的不可变集合
-(id)initWithFirstName:(NSString_)firstName andLastName:(NSString_)lastName;
-(void)addFriend:(EOCPerson*)person;
-(void)removeFriend:(EOCPerson*)person;
@end
在这里,我们将friends属性设置为不可变的set。然后,提供了来增加和删除这个set里的元素的公共接口。 在实现文件里:
@interface EOCPerson ()
@property (nonatomic, copy, readwrite) NSString _firstName;
@property (nonatomic, copy, readwrite) NSString _lastName;
@end
@implementation EOCPerson {
NSMutableSet *_internalFriends; //实现文件里的可变集合
}
-(NSSet*)friends {
return [_internalFriends copy]; //get方法返回的永远是可变set的不可变型
}
-(void)addFriend:(EOCPerson*)person {
[_internalFriends addObject:person]; //在外部增加集合元素的操作
//do something when add element
}
-(void)removeFriend:(EOCPerson*)person {
[_internalFriends removeObject:person]; //在外部移除元素的操作
//do something when remove element
}
-(id)initWithFirstName:(NSString_)firstName andLastName:(NSString_)lastName {
if ((self = [super init])) {
_firstName = firstName;
_lastName = lastName;
_internalFriends = [NSMutableSet new];
}
return self;
}
我们可以看到,在实现文件里,保存一个可变set来记录外部的增删操作。 这里最重要的代码是:
-(NSSet*)friends {
return [_internalFriends copy];
}
这个是friends属性的获取方法:它将当前保存的可变set复制了一不可变的set并返回。因此,外部读取到的set都将是不可变的版本。
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;
不推荐这样写:
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height;
- (void)doSomethingWith:(NSString *)theFoo
rect:(CGRect)theRect
interval:(CGFloat)theInterval
{
//Implementation
}
@interface ViewController ()
- (void)basicConfiguration;
@end
@implementation ViewController
- (void)basicConfiguration
{
//Do some basic configuration
}
@end
- (NSString *)descriptionWithLocale:(id)locale;
refresh
为首。update
为首。- (void)refreshHeaderViewWithCount:(NSUInteger)count;
- (void)updateDataSourceWithViewModel:(ViewModel*)viewModel;
@protocol ZOCFeedParserDelegate <NSObject>
@optional
- (void)feedParserDidStart:(ZOCFeedParser *)parser;
- (void)feedParser:(ZOCFeedParser *)parser didParseFeedInfo:(ZOCFeedInfoDTO *)info;
- (void)feedParser:(ZOCFeedParser *)parser didParseFeedItem:(ZOCFeedItemDTO *)item;
- (void)feedParserDidFinish:(ZOCFeedParser *)parser;
- (void)feedParser:(ZOCFeedParser *)parser didFailWithError:(NSError *)error;@end
@interface ZOCFeedParser : NSObject
@property (nonatomic, weak) id <ZOCFeedParserDelegate> delegate;
@property (nonatomic, strong) NSURL *url;
- (id)initWithURL:(NSURL *)url;
- (BOOL)start;
- (void)stop;
@end
然后在`ZOCTableViewController`里面传入`ZOCFeedParser`,并遵循其代理方法,实现feed的拉取功能。
@interface ZOCTableViewController : UITableViewController<ZOCFeedParserDelegate>
- (instancetype)initWithFeedParser:(ZOCFeedParser *)feedParser;
@end
具体应用:
NSURL *feedURL = [NSURL URLWithString:@"http://bbc.co.uk/feed.rss"];
ZOCFeedParser *feedParser = [[ZOCFeedParser alloc] initWithURL:feedURL];
ZOCTableViewController *tableViewController = [[ZOCTableViewController alloc] initWithFeedParser:feedParser];
feedParser.delegate = tableViewController;
OK,现在我们实现了需求:在`ZOCTableViewController`里面存放了一个`ZOCFeedParser`对象来处理feed的拉取功能。 但这里有一个严重的耦合问题:`ZOCTableViewController`只能通过`ZOCFeedParser`对象来处理feed的拉取功能。 于是我们重新审视一下这个需求:其实我们实际上只需要`ZOCTableViewController`拉取feed就可以了,而具体是由哪个对象来拉取,`ZOCTableViewController`并不需要关心。 也就是说,我们需要提供给`ZOCTableViewController`的是一个更范型的对象,这个对象具备了拉取feed的功能就好了,而不应该仅仅局限于某个具体的对象(`ZOCFeedParser`)。所以,刚才的设计需要重新做一次修改:
@protocol ZOCFeedParserDelegate <NSObject>
@optional
- (void)feedParserDidStart:(id<ZOCFeedParserProtocol>)parser;
- (void)feedParser:(id<ZOCFeedParserProtocol>)parser didParseFeedInfo:(ZOCFeedInfoDTO *)info;
- (void)feedParser:(id<ZOCFeedParserProtocol>)parser didParseFeedItem:(ZOCFeedItemDTO *)item;
- (void)feedParserDidFinish:(id<ZOCFeedParserProtocol>)parser;
- (void)feedParser:(id<ZOCFeedParserProtocol>)parser didFailWithError:(NSError *)error;@end
@protocol ZOCFeedParserProtocol <NSObject>
@property (nonatomic, weak) id <ZOCFeedParserDelegate> delegate;
@property (nonatomic, strong) NSURL *url;
- (BOOL)start;
- (void)stop;
@end
而原来的`ZOCFeedParser`仅仅是需要遵循上面这个协议就具备了拉取feed的功能:
@interface ZOCFeedParser : NSObject <ZOCFeedParserProtocol>
- (id)initWithURL:(NSURL *)url;//仅仅需要通过传入url即可,其他事情都交给ZOCFeedParserProtocol@end
而且,`ZOCTableViewController`也不直接依赖于`ZOCFeedParser`对象,我们只需要传给它一个遵循`<ZOCFeedParserProtocol>`的对象即可。
@interface ZOCTableViewController : UITableViewController <ZOCFeedParserDelegate>
- (instancetype)initWithFeedParser:(id<ZOCFeedParserProtocol>)feedParser;
@end
这样一来,`ZOCTableViewController`和`ZOCFeedParser`之间就没有直接的关系了。以后,如果我们想:
ZOCFeedParserProtocol.h
文件。ZOCFeedParserProtocol.h
即可。- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
这个方法正确地体现了代理的作用:委托者(tableview)告诉代理(控制器)“我的某个cell被点击了”。但是,UITableViewDelegate的方法列表里还有这个方法:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
该方法的作用是 由控制器来告诉tabievlew的行高,也就是说,它的信息流是从控制器(数据源)到委托者(tableview)的。准确来讲,它应该是一个数据源方法,而不是代理方法。 在UITableViewDataSource中,就有标准的数据源方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
这个方法的作用就是让tableview向控制器拉取一个section数量的数据。 所以,在我们设计一个视图控件的代理和数据源时,一定要区分好二者的区别,合理地划分哪些方法属于代理方法,哪些方法属于数据源方法。
if ([self.delegate respondsToSelector:@selector(signUpViewControllerDidPressSignUpButton:)]) {
[self.delegate signUpViewControllerDidPressSignUpButton:self];
}
@interface ShopViewController () <UIGestureRecognizerDelegate,
HXSClickEventDelegate,
UITableViewDelegate,
UITableViewDataSource>
@protocol ZOCServiceDelegate <NSObject>@optional- (void)generalService:(ZOCGeneralService *)service didRetrieveEntries:(NSArray *)entries;
@end
//父类
ZOCSalesListViewController
//子类
ZOCDaySalesListViewController
ZOCMonthSalesListViewController
- (instancetype)init {
self = [super init]; // call the designated initializer
if (self) {
// Custom initialization
}
return self;
}
@implementation ZOCEvent
//指定初始化方法
- (instancetype)initWithTitle:(NSString *)title date:(NSDate *)date
location:(CLLocation *)location
{
self = [super init];
if (self) {
_title = title;
_date = date;
_location = location;
}
return self;
}
//间接初始化方法
- (instancetype)initWithTitle:(NSString *)title date:(NSDate *)date
{
return [self initWithTitle:title date:date location:nil];
}
//间接初始化方法
- (instancetype)initWithTitle:(NSString *)title
{
return [self initWithTitle:title date:[NSDate date] location:nil];
}
@end
注意事项2:如果直接父类有指定初始化方法,则必须调用其指定初始化方法
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
注意事项3:如果想在当前类自定义一个新的全能初始化方法,则需要如下几个步骤
看一个标准的例子:
@implementation ZOCNewsViewController
//新的指定初始化方法
- (id)initWithNews:(ZOCNews *)news {
self = [super initWithNibName:nil bundle:nil];
if (self) {
_news = news;
}
return self;
}
// 重载父类的初始化方法
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
return [self initWithNews:nil];
}
@end
在这里,重载父类的初始化方法并在内部调用新定义的指定初始化方法的原因是你不能确定调用者调用的就一定是你定义的这个新的指定初始化方法,而不是原来从父类继承来的指定初始化方法。
假设你没有重载父类的指定初始化方法,而调用者却恰恰调用了父类的初始化方法。那么调用者可能永远都调用不到你自己定义的新指定初始化方法了。
而如果你成功定义了一个新的指定初始化方法并能保证调用者一定能调用它,你最好要在文档中明确写出哪一个才是你定义的新初始化方法。或者你也可以使用编译器指令__attribute__((objc_designated_initializer))
来标记它。
将instancetype关键字作为返回值的时候,可以让编译器进行类型检查,同时适用于子类的检查,这样就保证了返回类型的正确性(一定为当前的类对象或实例对象)
推荐这样写:
@interface ZOCPerson
+ (instancetype)personWithName:(NSString *)name;
@end
不推荐这样写:
@interface ZOCPerson
+ (id)personWithName:(NSString *)name;
@end
有时,类A需要将类B的实例变量作为它公共API的属性。这个时候,我们不应该引入类B的头文件,而应该使用向前声明(forward declaring)使用class关键字,并且在A的实现文件引用B的头文件。
// EOCPerson.h
#import <Foundation/Foundation.h>
@class EOCEmployer;
@interface EOCPerson : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, strong) EOCEmployer *employer;//将EOCEmployer作为属性
@end
// EOCPerson.m
#import "EOCEmployer.h"
这样做有什么优点呢:
- 不在A的头文件中引入B的头文件,就不会一并引入B的全部内容,这样就减少了编译时间。
- 可以避免循环引用:因为如果两个类在自己的头文件中都引入了对方的头文件,那么就会导致其中一个类无法被正确编译。
但是个别的时候,必须在头文件中引入其他类的头文件:
主要有两种情况:
- 该类继承于某个类,则应该引入父类的头文件。
- 该类遵从某个协议,则应该引入该协议的头文件。而且最好将协议单独放在一个头文件中。
#pragma mark - Life Cycle Methods
- (instancetype)init
- (void)dealloc
- (void)viewWillAppear:(BOOL)animated
- (void)viewDidAppear:(BOOL)animated
- (void)viewWillDisappear:(BOOL)animated
- (void)viewDidDisappear:(BOOL)animated
#pragma mark - Override Methods
#pragma mark - Intial Methods
#pragma mark - Network Methods
#pragma mark - Target Methods
#pragma mark - Public Methods
#pragma mark - Private Methods
#pragma mark - UITableViewDataSource
#pragma mark - UITableViewDelegate
#pragma mark - Lazy Loads
#pragma mark - NSCopying
#pragma mark - NSObject Methods
推荐这样写:
@interface NSDate (ZOCTimeExtensions)
- (NSString *)zoc_timeAgoShort;
@end
不推荐这样写:
@interface NSDate (ZOCTimeExtensions)
- (NSString *)timeAgoShort;
@end
一个类可能会有很多公共方法,而且这些方法往往可以用某种特有的逻辑来分组。我们可以利用Objecctive-C的分类机制,将类的这些方法按一定的逻辑划入几个分区中。
举个��:
先看一个没有使用无分类的类:
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, strong, readonly) NSArray *friends;
- (id)initWithFirstName:(NSString*)firstName andLastName:(NSString*)lastName;
/* Friendship methods */
- (void)addFriend:(EOCPerson*)person;
- (void)removeFriend:(EOCPerson*)person;
- (BOOL)isFriendsWith:(EOCPerson*)person;
/* Work methods */
- (void)performDaysWork;
- (void)takeVacationFromWork;
/* Play methods */
- (void)goToTheCinema;
- (void)goToSportsGame;
@end
分类之后:
#import <Foundation/Foundation.h>
@interface EOCPerson : NSObject
@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;
@property (nonatomic, strong, readonly) NSArray *friends;
- (id)initWithFirstName:(NSString*)firstName
andLastName:(NSString*)lastName;
@end
@interface EOCPerson (Friendship)
- (void)addFriend:(EOCPerson*)person;
- (void)removeFriend:(EOCPerson*)person;
- (BOOL)isFriendsWith:(EOCPerson*)person;
@end
@interface EOCPerson (Work)
- (void)performDaysWork;
- (void)takeVacationFromWork;
@end
@interface EOCPerson (Play)
- (void)goToTheCinema;
- (void)goToSportsGame;
@end
其中,FriendShip分类的实现代码可以这么写:
// EOCPerson+Friendship.h
#import "EOCPerson.h"
@interface EOCPerson (Friendship)
- (void)addFriend:(EOCPerson*)person;
- (void)removeFriend:(EOCPerson*)person;
- (BOOL)isFriendsWith:(EOCPerson*)person;
@end
// EOCPerson+Friendship.m
#import "EOCPerson+Friendship.h"
@implementation EOCPerson (Friendship)
- (void)addFriend:(EOCPerson*)person {
/* ... */
}
- (void)removeFriend:(EOCPerson*)person {
/* ... */
}
- (BOOL)isFriendsWith:(EOCPerson*)person {
/* ... */
}
@end
注意:在新建分类文件时,一定要引入被分类的类文件。
通过分类机制,可以把类代码分成很多个易于管理的功能区,同时也便于调试。因为分类的方法名称会包含分类的名称,可以马上看到该方法属于哪个分类中。
利用这一点,我们可以创建名为Private的分类,将所有私有方法都放在该类里。这样一来,我们就可以根据private一词的出现位置来判断调用的合理性,这也是一种编写“自我描述式代码(self-documenting)”的办法。
单例对象不应该暴露出任何属性,也就是说它不能作为让外部存放对象的容器。它应该是一个处理某些特定任务的工具,比如在iOS中的GPS和加速度传感器。我们只能从他们那里得到一些特定的数据。
推荐这样写:
+ (instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
不推荐这样写:
+ (instancetype)sharedInstance {
static id sharedInstance;
@synchronized(self) {
if (sharedInstance == nil) { sharedInstance = [[MyClass alloc] init];
} }
return sharedInstance;
}
判断两个person类是否相等的合理做法:
- (BOOL)isEqual:(id)object {
if (self == object) { return YES; //判断内存地址
}
if (![object isKindOfClass:[ZOCPerson class]]) {
return NO; //是否为当前类或派生类 }
return [self isEqualToPerson:(ZOCPerson *)object];
}
//自定义的判断相等性的方法
- (BOOL)isEqualToPerson:(Person *)person {
if (!person) { return NO;
} BOOL namesMatch = (!self.name && !person.name) || [self.name isEqualToString:person.name]; BOOL birthdaysMatch = (!self.birthday && !person.birthday) || [self.birthday isEqualToDate:person.birthday]; return haveEqualNames && haveEqualBirthdays;
}
一个函数(方法)必须有一个字符串文档来解释,除非它:
而其余的,包括公开接口,重要的方法,分类,以及协议,都应该伴随文档(注释):
建议这样写:
/This comment serves to demonstrate the format of a doc string.
Note that the summary line is always at most one line long, and after the opening block comment,
and each line of text is preceded by a single space.
*/
看一个指定初始化方法的注释:
/
* Designated initializer. *
* @param store The store for CRUD operations.
* @param searchService The search service used to query the store.
* @return A ZOCCRUDOperationsStore object.
*/
- (instancetype)initWithOperationsStore:(id<ZOCGenericStoreProtocol>)store searchService:(id<ZOCGenericSearchServiceProtocol>)searchService;
多个线程执行同一份代码时,很可能会造成数据不同步。建议使用GCD来为代码加锁的方式解决这个问题。
_syncQueue = dispatch_queue_create("com.effectiveobjectivec.syncQueue", NULL);
//读取字符串
- (NSString*)someString {
__block NSString *localSomeString;
dispatch_sync(_syncQueue, ^{
localSomeString = _someString;
});
return localSomeString;
}
//设置字符串
- (void)setSomeString:(NSString*)someString {
dispatch_sync(_syncQueue, ^{
_someString = someString;
});
}
这样一来,读写操作都在串行队列进行,就不容易出错。
但是,还有一种方法可以让性能更高:
_syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//读取字符串
- (NSString*)someString {
__block NSString *localSomeString;
dispatch_sync(_syncQueue, ^{
localSomeString = _someString;
});
return localSomeString;
}
显然,数据的正确性主要取决于写入操作,那么只要保证写入时,线程是安全的,那么即便读取操作是并发的,也可以保证数据是同步的。
这里的dispatch_barrier_async
方法使得操作放在了同步队列里“有序进行”,保证了写入操作的任务是在串行队列里。
在打印我们自己定义的类的实例对象时,在控制台输出的结果往往是这样的:object = <EOCPerson: 0x7fd9a1600600>
这里只包含了类名和内存地址,它的信息显然是不具体的,远达不到调试的要求。
但是!如果在我们自己定义的类覆写description方法,我们就可以在打印这个类的实例时输出我们想要的信息。
例如:
- (NSString*)description {
return [NSString stringWithFormat:@"<%@: %p, %@ %@>", [self class], self, firstName, lastName];
}
在这里,显示了内存地址,还有该类的所有属性。
而且,如果我们将这些属性值放在字典里打印,则更具有可读性:
- (NSString*)description {
return [NSString stringWithFormat:@"<%@: %p, %@>",[self class],self,
@{ @"title":_title,
@"latitude":@(_latitude),
@"longitude":@(_longitude)}
];
}
输出结果:
location = <EOCLocation: 0x7f98f2e01d20, {
latitude = "51.506";
longitude = 0;
title = London;
}
我们可以看到,通过重写description
方法可以让我们更加了解对象的情况,便于后期的调试,节省开发时间。
如果我们缓存使用得当,那么应用程序的响应速度就会提高。只有那种“重新计算起来很费事的数据,才值得放入缓存”,比如那些需要从网络获取或从磁盘读取的数据。
在构建缓存的时候很多人习惯用NSDictionary或者NSMutableDictionary,但是作者建议大家使用NSCache,它作为管理缓存的类,有很多特点要优于字典,因为它本来就是为了管理缓存而设计的。
建议将通知的名字作为常量,保存在一个专门的类中:
// Const.h
extern NSString * const ZOCFooDidBecomeBarNotification
// Const.m
NSString * const ZOCFooDidBecomeBarNotification = @"ZOCFooDidBecomeBarNotification";
通知必须要在对象销毁之前移除掉。
对于某些暂时不用,以后可能用到的临时变量,为了避免警告,我们可以使用如下方法将这个警告消除:
- (NSInteger)giveMeFive {
NSString *foo;
#pragma unused (foo)
return 5;
}
- (NSInteger)divide:(NSInteger)dividend by:(NSInteger)divisor {
#error Whoa, buddy, you need to check for zero here!
return (dividend / divisor);
}
- (float)divide:(float)dividend by:(float)divisor {
#warning Dude, don't compare floating point numbers like this!
if (divisor != 0.0) {
return (dividend / divisor);
} else { return NAN;
}
}
iOS开发者交流群:446310206
文章浏览阅读6.3k次。1、首先按照正常的建立方法把wifi建立好,然后在软件中心收缩 network ,点击安装 kde5-nm-connection-editor。2、在终端里输入kde5-nm-connection-editor 打开应用。3、点击刚才建立的wifi,点击编辑,把ad-hoc改成接入点即可。_kde5-nm-connection-editor
文章浏览阅读224次。Web3——互联网发展的“下一阶段”,预计它将以区块链技术为基础。在所有定义Web3的说法中,也许没有一个比去中心化更重要或普遍。虽然加密货币处于这场运动的最前沿,但科技行业的一些人认为,去中心化是互联网不可避免的进化步骤,将影响各行各业的业务。..._传统企业 web3 和去中心化做的 11 个准备
文章浏览阅读8.4k次。转自: http://www.linuxidc.com/Linux/2011-11/47120.htmAndroid 开机会出现3个画面:第一个就是 linux 系统启动,出现Linux小企鹅画面(reboot);Linux Kernel引导启动后,加载该图片,涉及到的代码在如下的目录中:/kernel/trunk/drivers/video/fbmem.c/kerne_安卓9.0 bootlogo
文章浏览阅读1k次。pip 安装、升级、删除提示以下错误:Cannot uninstall ‘requests’. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.强制安装..._cannot uninstall pip
文章浏览阅读262次。数据结构与算法,算法导论,期末复习看完这一篇文章就够了!_假设t(n)是定义为t(n)=3·t(n/3)+n的递归函数,尝试求解t(n)。
文章浏览阅读796次,点赞22次,收藏11次。既然是要面试,那么就少不了刷题,实际上春节回家后,哪儿也去不了,我自己是刷了不少面试题的,所以在面试过程中才能够做到心中有数,基本上会清楚面试过程中会问到哪些知识点,高频题又有哪些,所以刷题是面试前期准备过程中非常重要的一点。其实现在已经到了91篇文章,后面新增的文章,目录不再此文章中更新了, 本文是一个专栏,只需要购买专栏就可以看所有文章,并不是一篇文章付费一次哈。目前专栏一共69篇文章,文章持续增加中,每增加10个小伙伴订阅专栏,就新增1-5篇,随着招聘岗位技术栈的变动而变动,确保都是最新的。
文章浏览阅读2.2w次,点赞3次,收藏16次。像素与毫米的转换转换还需要知道另一个参数:DPI(每英寸多少点)象素数 / DPI = 英寸数英寸数 * 25.4 = 毫米数对于显示设备,不管是打印机还是屏幕,都有一种通用的方法先用GetDeviceCaps(设备句柄,LOGPIXELSX)或者GetDeviceCaps(设备句柄,LOGPIXELSY)获得设备每英寸的像素数分别记为:px 和 py一英寸等于_显微镜像素和毫米换算
文章浏览阅读1w次,点赞5次,收藏18次。蒙特·卡罗方法(Monte Carlo method),也称统计模拟方法,是二十世纪四十年代中期由于科学技术的发展和电子计算机的发明,而被提出的一种以概率统计理论为指导的一类非常重要的数值计算方法。是指使用随机数(或更常见的伪随机数)来解决很多计算问题的方法。与它对应的是确定性算法。蒙特·卡罗方法在金融工程学,宏观经济学,计算物理学(如粒子输运计算、量子热力学计算、空气动力学计算)等领域应用广泛。..._python用蒙特卡罗方法计算圆周率
文章浏览阅读334次。(给程序员的那些事加星标,每天看趣图)微软:你是哪种垃圾?↓↓↓(图来自@妖公_Yakoo)往期趣图(点击下方图片可跳转阅读)关注「程序员的那些事」加星标,不错过趣图(商..._你是什么垃圾趣图
文章浏览阅读195次。特征筛选是机器学习和数据分析中非常重要的步骤,它有助于选择对目标变量具有预测能力的最佳特征。在R语言中,我们可以使用信息价值(IV)和证据权重(WOE)作为评估指标来进行特征筛选。通过这种方法,你可以选择对目标变量有最大预测能力的特征,从而提高模型的性能和泛化能力。你可以根据实际需求修改代码中的参数,例如选择不同的IV值阈值或选择不同的特征数量。根据IV值排序后,我们可以选择IV值较高的特征进行进一步的筛选。一旦我们准备好了数据,我们可以开始使用IV和WOE进行特征筛选。接下来,我们需要准备数据集。_r语言woe
文章浏览阅读486次。熟悉 Linux 系统的同学都知道,它高效主要体现在命令行。通过命令行,可以将很多简单的命令,通过自由的组合,得到非常强大的功能。命令行也就意味着可以自动化,自动化会使你的工作更高效,释放很多手工操作,让你有更多的时间去做更有意义的事情。这篇文章,会分享一些非常实用小技巧,希望能够帮助你提高工作效率,学完就能够用得上!1. 快速清空文件的方法快速清空一个文件,有 N 种方法,我比较喜欢下边这种,因为它最短$>access.log不过瘾?好吧,我也顺便总结下,其它几种.._linux小技巧
文章浏览阅读100次。因为各种事宜处理了一些时间,今天我们书接上文。继HTTP协议之后,以白话文的讲一讲什么是TCP/IP?理解片面、不足的地方请大神们好好指教一番。那么let's begin1.TCP/IP 协议的定义(图片来源于网络)这个是当今运行的网络七层表示图(并不完整),至下而上数分别是1.物理层、2.数据链路层、3.网络层、4.传输层、5.会话层、6.表示层、7..._没啥用tcp/ip协议而不是用ios协议