美文网首页
我爱编程,我

我爱编程,我

作者: 翘起地球表面 | 来源:发表于2017-03-10 22:19 被阅读350次

    实战项目经验浅谈,不足之处还需指出。

    不推荐写法,都是我曾经代码里编写的代码,翻阅之前的代码简直就是渣,各种不规范,为了逼迫自己规范写法,不墨守成规,勇于学习新的知识,简单的写几个编码案例,仅供参考。

    NSString,NSDictionary, NSArray,和NSNumber的字面值应该在创建这些类的不可变实例时被使用。请特别注意nil值不能传入NSArray和NSDictionary字面值,因为这样会导致crash

    推荐写法:

    NSArray *array=@[@”test”,@”ui”,@”iOS”];

    不推荐写法:

    NSArray *array=[NSAraay arryWithObjects:@”test”,@”ui”,@”iOS”];

    推荐写法:

    NSDirectory *dir=@{@“SEX”:@”MAN”,@”NAME”:@”HUANG”};

    不推荐写法:

    NSDirectory *dir=[NSDirectory directoryWithObjectsAndKeys:@”SEX”:@”MAN”,@”NAME”:@”ZHU”,nil];

    推荐写法:

    NSNumber*shouldUseLiterals = @YES;

    不推荐写法:

    NSNumber *double=[NSNumber numberWithBool:YES];

    推荐写法:

    NSNumber*buildingStreetNumber = @10;

    不推荐写法:

    NSNumber *buildNumber=[NSNumber numberWithInteger:10];

    Ps:曾经面试时候被问过,NSArray能不能直接存Int类型。

    2.常量

    常量是容易重复被使用和无需通过查找和代替就能快速修改值。常量应该使用static来声明而不是使用#define,除非显式地使用宏。

    推荐写法:

    1、static NSString * const CompanyName = @"jbt.com";

    2、static CGFloat const   ImageHeight = 64.0;

    不推荐写法:

    1、#defineCompanyName  @"huangyiliang.com";

    2、#defineImageThumbnailHeight 50.0;

    3.CGRect

    在使用CGRect时候,应该使用当访问CGRect里的x, y,

    width,或height时,应该使用CGGeometry函数而不是直接通过结构体来访问。引用Apple的CGGeometry:

    例如:推荐写法

    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);

    4.单例模式

    单例对象应该使用线程安全模式来创建共享实例。

    +(instancetype)sharedInstance{

    Static id sharedInstance =nil;

    Staticdispatch_once_t onceToken;

    dispatch_once(&onceToken,^{

    sharedInstance=[[self alloc]init];

    });

    Return sharedInstance;

    }

    推荐使用这种,因为苹果官方文档推荐使用在GCD方式,因为GCD在处理多核上能力强。

    为了不必要每次都要写单列方法,可以抽象出宏命令来创建就好了

    // .h

    #define singleton_interface(class) +(instancetype)shared##class;

    // .m

    #define singleton_implementation(class) \

    static class *_instance; \

    \

    + (id)allocWithZone:(struct _NSZone *)zone\

    { \

    static dispatch_once_t onceToken; \

    dispatch_once(&onceToken, ^{ \

    _instance = [super allocWithZone:zone]; \

    }); \

    \

    return _instance; \

    } \

    \

    + (instancetype)shared##class \

    { \

    if (_instance == nil) { \

    _instance = [[class alloc] init]; \

    }\

    \

    return _instance; \

    }

    ps:单列也是经常面试题目之一,问的出现频率比较高~

    相关文章

      网友评论

          本文标题: 我爱编程,我

          本文链接:https://www.haomeiwen.com/subject/zhwogttx.html