IOS中的swift和oc关于对象模型的description方法重写
生活随笔
收集整理的這篇文章主要介紹了
IOS中的swift和oc关于对象模型的description方法重写
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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);
}
控制臺打印內容
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()//KVCself.setValuesForKeys(dict)}init(dict: [String: Any],title: String){super.init()//KVCself.setValuesForKeys(dict)}override var description: String{let keys = ["access_token","expires_in","uid"]//數組return dictionaryWithValues(forKeys: keys).description} }測試主要代碼,自己寫一個函數去調用一下
let dictTest1: [String: Any] = ["access_token": "2.00tIZE123we455489c55clskLbD", "expires_in": "157679999", "uid": "5335345699"] let account1 = UserAccount(dict: dictTest1, title: "") debugPrint(account1)日志:
["access_token": 2.11tI789pF0l1kIyhfdsf1c55clskLbD, "expires_in": 15764579999, "uid": 5564567845699]順帶把java的也說一下,
java一般重寫toString方法,alt + insert鍵 可以重寫,蘋果電腦idea的快捷鍵是cmd + N,為了返璞歸真,我這里沒有使用Lombok,而是使用原生的方法
我用junit測試的,也可以使用靜態的main方法測試
@Testvoid 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 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的IOS中的swift和oc关于对象模型的description方法重写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 伤肾的九个恶习及解决办法(图)
- 下一篇: IOS中的枚举的写法...