IOS中的swift和oc关于对象模型的description方法重写
先讲OC的,oc比较重要,放在最前面.
首先创建一个cocoa Touch Class,继承NSObject, 命名Person
点h文件写几个属性
#import <Foundation/Foundation.h>
@interface AHLJPerson : NSObject
@property(nonatomic,copy)NSString * name;
@property(nonatomic,assign)int age;
@property(nonatomic,assign)double height;
@end
重写description方法
- -(NSString *)description
{
return [NSString stringWithFormat:@"<%p %@,{name: %@,age: %d,height: %f}>",self, [self class],self.name,self.age,self.height ];
}
书写的格式较多,我认为这种格式较规范,描述的也清楚.
重写触摸屏幕事件 - -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
AHLJPerson *p1 = [[AHLJPerson alloc] init];
p1.name = @“jack”;
p1.age = 18;
p1.height = 178;
AHLJPerson *p2 = [[AHLJPerson alloc] init];
p2.name = @“rose”;
p2.age = 19;
p2.height = 160;
NSLog(@"%@",p1);
NSLog(@"%@",p2);
}
控制台打印内容
2021-10-18 13:29:55.553929+0800 decriptionTest[9278:202074] <0x600002a757c0 AHLJPerson,{name: jack,age: 18,height: 178.000000}>
2021-10-18 13:29:55.554015+0800 decriptionTest[9278:202074] <0x600002a757e0 AHLJPerson,{name: rose,age: 19,height: 160.000000}>
swift的description方法;
import UIKit
class UserAccount: NSObject {
@objc var access_token: String?
@objc var expires_in: TimeInterval = 0
@objc var uid: String?
init(dict: [String: NSObject]){
super.init()
//KVC
self.setValuesForKeys(dict)
}
override var description: String{
let keys = ["access_token","expires_in","uid"]//数组
return dictionaryWithValues(forKeys: keys).description
}
}
日志:
["access_token": 2.11tI789pF0l1kIyhfdsf1c55clskLbD, "expires_in": 15764579999, "uid": 5564567845699]
顺带把java的也说一下,
java一般重写toString方法,alt + insert键 可以重写,苹果电脑idea的快捷键是cmd + N,为了返璞归真,我这里没有使用Lombok,而是使用原生的方法
package com.example.demo.pojo;
public class Person {
private String name;
private int age;
private double height;
public Person(){}
public Person(String name, int age, double height) {
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", height=" + height +
'}';
}
}
我用junit测试的,也可以使用静态的main方法测试
@Test
void contextLoads() {
Person p1 = new Person("jack",18,178);
Person p2 = new Person("rose",17,178);
System.out.println(p1);
System.out.println(p2);
System.out.println(p1.getClass());
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
}
日志:
Person{name='jack', age=18, height=178.0}
Person{name='rose', age=17, height=178.0}
class com.example.demo.pojo.Person
33558975
1373220972