前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS - 代码Review (四)

iOS - 代码Review (四)

原创
作者头像
Wilbur-L
修改2021-11-04 15:29:03
3610
修改2021-11-04 15:29:03
举报
文章被收录于专栏:iOS底层原理iOS底层原理

一·实现Description方法

在调试程序中经常用NSLog(@"%@",self.object);来打印数据

代码语言:javascript
复制
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic, copy, readonly) NSString *firstName;
@property (nonatomic, copy, readonly) NSString *lastName;

- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName;
@end


@implementation Person
- (instancetype)initWithFirstName:(NSString *)firstName lastName:(NSString *)lastName {
    if (self = [super init]) {
        _firstName = [firstName copy];
        _lastName = [lastName copy];
    }
    return self;
}

@end

那么该类的描述方法可以这样写

代码语言:javascript
复制
 - (NSString *)description {
     return [NSString stringWithFormat:@"< %@ : %p, \" %@ %@\">", [self class], self, _firstName, _lastName ];
 }
 
 //person = <Person : 0x7f9996c38250, "levin eeo">

如果想修改LLDB调试的po指令打印出来的消息那么可以重写上面的方法,只需要添加debug

代码语言:javascript
复制
- (NSString *)debugDescription {
    return [NSString stringWithFormat:@"< %@ : %p, \" %@ %@\">", [self class], self, _firstName, _lastName ];
}

// po person 
// (Person *) $0 = 0x7f9996c38250 <Person : 0x7f9996c38250, "levin eoo">

二·尽量使用不可变对象

代码语言:javascript
复制
#import <Foundation/Foundation.h>

@interface PointServer : NSObject
@property (nonatomic, copy) NSString *identifier;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) float xPoint;
@property (nonatomic, assign) float yPoint;

 - (instancetype)initWithIdentifier:(NSString *)identifier title:(NSString *)title x:(float)x y:(float)y;
对象中的值通过网络服务获取,在与网络服务通信过程中,通过identifer来代表景点,用服务器所提供的数据创建好某个点后
就不需要改动了.如果用其他语言来写比如golang会通过方法名大小写来控制外部访问权限,又例如Swift的private 和 public
所以为了把PointServer 做成不可变的类,需要把所有属性声明成readonly


@property (nonatomic, copy, readonly) NSString *identifier;
@property (nonatomic, copy, readonly) NNStrint *title;
@property (nonatomic, assign, readonly) float xPoint;
@property (nonatomic, assign, readonly) float yPoint;


如果强行改动这些值,编译器会报错.对象中的属性值可读但不可写。这就保证了PointServer类中的各个数据之间是相互
协调的。于是,开发者在使用对象肯定对底层数据reaonly的数据不会改动。因此,对象本身的数据结构不可能出现不一致的想象


@end

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一·实现Description方法
  • 二·尽量使用不可变对象
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档