Runtime的應用

來自:http://www.imlifengfeng.com/blog/?p=397 1、快速歸檔

  • (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { unsigned int outCount; Ivar * ivars = class_copyIvarList([self class], &outCount); for (int i = 0; i < outCount; i ++) { Ivar ivar = ivars[i]; NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)]; [self setValue:[aDecoder decodeObjectForKey:key] forKey:key]; } } return self; }

  • (void)encodeWithCoder:(NSCoder *)aCoder { unsigned int outCount; Ivar * ivars = class_copyIvarList([self class], &outCount); for (int i = 0; i < outCount; i ++) { Ivar ivar = ivars[i]; NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)]; [aCoder encodeObject:[self valueForKey:key] forKey:key]; } }

2、Json到Model的轉化

  • (instancetype)initWithDict:(NSDictionary *)dict {

    if (self = [self init]) { //(1)獲取類的屬性及屬性對應的類型 NSMutableArray * keys = [NSMutableArray array]; NSMutableArray * attributes = [NSMutableArray array]; /* * 例子 * name = value3 attribute = T@"NSString",C,N,V_value3 * name = value4 attribute = T^i,N,V_value4 */ unsigned int outCount; objc_property_t * properties = class_copyPropertyList([self class], &outCount); for (int i = 0; i < outCount; i ++) { objc_property_t property = properties[i]; //通過property_getName函數獲得屬性的名字 NSString * propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; [keys addObject:propertyName]; //通過property_getAttributes函數可以獲得屬性的名字和@encode編碼 NSString * propertyAttribute = [NSString stringWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding]; [attributes addObject:propertyAttribute]; } //立即釋放properties指向的內存 free(properties);

      //(2)根據類型給屬性賦值for (NSString * key in keys) {if ([dict valueForKey:key] == nil) continue;[self setValue:[dict valueForKey:key] forKey:key];}
    復制代碼

    } return self; }

3、Category添加屬性并生成getter和setter方法 #import <Foundation/Foundation.h>

@interface NSArray (MyCategory) //不會生成添加屬性的getter和setter方法,必須我們手動生成 @property (nonatomic, copy) NSString *blog; @end

#import "NSArray+MyCategory.h" #import <objc/runtime.h>

@implementation NSArray (MyCategory)

// 定義關聯的key static const char *key = "blog";

/** blog的getter方法 */

  • (NSString *)blog { // 根據關聯的key,獲取關聯的值。 return objc_getAssociatedObject(self, key); }

/** blog的setter方法 */

  • (void)setBlog:(NSString *)blog { // 第一個參數:給哪個對象添加關聯 // 第二個參數:關聯的key,通過這個key獲取 // 第三個參數:關聯的value // 第四個參數:關聯的策略 objc_setAssociatedObject(self, key, blog, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } @end

4、Method Swizzling使用 #import "UIViewController+swizzling.h" #import <objc/runtime.h> @implementation UIViewController (swizzling)

  • (void)load { // 通過class_getInstanceMethod()函數從當前對象中的method list獲取method結構體,如果是類方法就使用class_getClassMethod()函數獲取。 Method fromMethod = class_getInstanceMethod([self class], @selector(viewDidLoad)); Method toMethod = class_getInstanceMethod([self class], @selector(swizzlingViewDidLoad)); /**
    • 我們在這里使用class_addMethod()函數對Method Swizzling做了一層驗證,如果self沒有實現被交換的方法,會導致失敗。
    • 而且self沒有交換的方法實現,但是父類有這個方法,這樣就會調用父類的方法,結果就不是我們想要的結果了。
    • 所以我們在這里通過class_addMethod()的驗證,如果self實現了這個方法,class_addMethod()函數將會返回NO,我們就可以對其進行交換了。 */ if (!class_addMethod([self class], @selector(swizzlingViewDidLoad), method_getImplementation(toMethod), method_getTypeEncoding(toMethod))) { method_exchangeImplementations(fromMethod, toMethod); } }

// 我們自己實現的方法,也就是和self的viewDidLoad方法進行交換的方法。

  • (void)swizzlingViewDidLoad { NSString *str = [NSString stringWithFormat:@"%@", self.class]; // 我們在這里加一個判斷,將系統的UIViewController的對象剔除掉 if(![str containsString:@"UI"]){ NSLog(@"統計打點 : %@", self.class); } [self swizzlingViewDidLoad]; } @end

5、Method Swizzling類簇 __NSArrayI才是NSArray真正的類 #import "NSArray+ MyArray.h" #import "objc/runtime.h" @implementation NSArray MyArray)

  • (void)load {//是加載文件到內存執行的方法 跟類的生命周期沒有關系 Method fromMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(objectAtIndex:)); Method toMethod = class_getInstanceMethod(objc_getClass("__NSArrayI"), @selector(my_objectAtIndex:)); method_exchangeImplementations(fromMethod, toMethod); }
  • (id)my_objectAtIndex:(NSUInteger)index { if (self.count-1 < index) { // 這里做一下異常處理,不然都不知道出錯了。 @try { return [self my_objectAtIndex:index]; } @catch (NSException *exception) { // 在崩潰后會打印崩潰信息,方便我們調試。 NSLog(@"---------- %s Crash Because Method %s ----------\n", class_getName(self.class), func); NSLog(@"%@", [exception callStackSymbols]); return nil; } @finally {} } else { return [self my_objectAtIndex:index]; } } @end

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391906.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391906.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391906.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用 VisualVM 進行性能分析及調優

https://www.ibm.com/developerworks/cn/java/j-lo-visualvm/轉載于:https://www.cnblogs.com/adolfmc/p/7238893.html

spring—事務控制

編程式事務控制相關對象 PlatformTransactionManager PlatformTransactionManager 接口是 spring 的事務管理器&#xff0c;它里面提供了我們常用的操作事務的方法。注意&#xff1a; PlatformTransactionManager 是接口類型&#xff0c;不同的 Dao 層技術則有不同的實現類 …

為什么印度盛產碼農_印度農產品價格的時間序列分析

為什么印度盛產碼農Agriculture is at the center of Indian economy and any major change in the sector leads to a multiplier effect on the entire economy. With around 17% contribution to the Gross Domestic Product (GDP), it provides employment to more than 50…

SAP NetWeaver

SAP的新一代企業級服務架構——NetWeaver    SAP NetWeaver是下一代基于服務的平臺&#xff0c;它將作為未來所有SAP應用程序的基礎。NetWeaver包含了一個門戶框架&#xff0c;商業智能和報表&#xff0c;商業流程管理&#xff08;BPM&#xff09;&#xff0c;自主數據管理&a…

NotifyMyFrontEnd 函數背后的數據緩沖區(一)

async.c的 static void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid) 函數中的主要邏輯是這樣的&#xff1a;復制代碼if (whereToSendOutput DestRemote) { StringInfoData buf; pq_beginmessage(&buf, A); //cursor 為 A pq…

最后期限 軟件工程_如何在軟件開發的最后期限內實現和平

最后期限 軟件工程D E A D L I N E…最后期限… As a developer, this is one of your biggest nightmares or should I say your enemy? Name it whatever you want.作為開發人員&#xff0c;這是您最大的噩夢之一&#xff0c;還是我應該說您的敵人&#xff1f; 隨便命名。 …

SQL Server的復合索引學習【轉載】

概要什么是單一索引,什么又是復合索引呢? 何時新建復合索引&#xff0c;復合索引又需要注意些什么呢&#xff1f;本篇文章主要是對網上一些討論的總結。一.概念單一索引是指索引列為一列的情況,即新建索引的語句只實施在一列上。用戶可以在多個列上建立索引&#xff0c;這種索…

leetcode 1423. 可獲得的最大點數(滑動窗口)

幾張卡牌 排成一行&#xff0c;每張卡牌都有一個對應的點數。點數由整數數組 cardPoints 給出。 每次行動&#xff0c;你可以從行的開頭或者末尾拿一張卡牌&#xff0c;最終你必須正好拿 k 張卡牌。 你的點數就是你拿到手中的所有卡牌的點數之和。 給你一個整數數組 cardPoi…

pandas處理excel文件和csv文件

一、csv文件 csv以純文本形式存儲表格數據 pd.read_csv(文件名)&#xff0c;可添加參數enginepython,encodinggbk 一般來說&#xff0c;windows系統的默認編碼為gbk&#xff0c;可在cmd窗口通過chcp查看活動頁代碼&#xff0c;936即代表gb2312。 例如我的電腦默認編碼時gb2312&…

tukey檢測_回到數據分析的未來:Tukey真空度的整潔實現

tukey檢測One of John Tukey’s landmark papers, “The Future of Data Analysis”, contains a set of analytical techniques that have gone largely unnoticed, as if they’re hiding in plain sight.John Tukey的標志性論文之一&#xff0c;“ 數據分析的未來 ”&#x…

spring— Spring與Web環境集成

ApplicationContext應用上下文獲取方式 應用上下文對象是通過new ClasspathXmlApplicationContext(spring配置文件) 方式獲取的&#xff0c;但是每次從容器中獲 得Bean時都要編寫new ClasspathXmlApplicationContext(spring配置文件) &#xff0c;這樣的弊端是配置文件加載多次…

Elasticsearch集群知識筆記

Elasticsearch集群知識筆記 Elasticsearch內部提供了一個rest接口用于查看集群內部的健康狀況&#xff1a; curl -XGET http://localhost:9200/_cluster/healthresponse結果&#xff1a; {"cluster_name": "format-es","status": "green&qu…

Item 14 In public classes, use accessor methods, not public fields

在public類中使用訪問方法&#xff0c;而非公有域 這標題看起來真晦澀。。解釋一下就是&#xff0c;如果類變成public的了--->那就使用getter和setter&#xff0c;不要用public成員。 要注意它的前提&#xff0c;如果是private的class&#xff08;內部類..&#xff09;或者p…

子集和與一個整數相等算法_背包問題的一個變體:如何解決Java中的分區相等子集和問題...

子集和與一個整數相等算法by Fabian Terh由Fabian Terh Previously, I wrote about solving the Knapsack Problem (KP) with dynamic programming. You can read about it here.之前&#xff0c;我寫過有關使用動態編程解決背包問題(KP)的文章。 你可以在這里閱讀 。 Today …

matplotlib圖表介紹

Matplotlib 是一個python 的繪圖庫&#xff0c;主要用于生成2D圖表。 常用到的是matplotlib中的pyplot&#xff0c;導入方式import matplotlib.pyplot as plt 一、顯示圖表的模式 1.plt.show() 該方式每次都需要手動show()才能顯示圖表&#xff0c;由于pycharm不支持魔法函數&a…

到2025年將保持不變的熱門流行技術

重點 (Top highlight)I spent a good amount of time interviewing SMEs, data scientists, business analysts, leads & their customers, programmers, data enthusiasts and experts from various domains across the globe to identify & put together a list that…

spring—SpringMVC的請求和響應

SpringMVC的數據響應-數據響應方式 頁面跳轉 直接返回字符串 RequestMapping(value {"/qq"},method {RequestMethod.GET},params {"name"})public String method(){System.out.println("controller");return "success";}<bea…

Maven+eclipse快速入門

1.eclipse下載 在無外網情況下&#xff0c;無法通過eclipse自帶的help-install new software輸入url來獲取maven插件&#xff0c;因此可以用集成了maven插件的免安裝eclipse(百度一下有很多)。 2.jdk下載以及環境變量配置 JDK是向前兼容的&#xff0c;可在Eclipse上選擇編譯器版…

源碼閱讀中的收獲

最近在做短視頻相關的模塊&#xff0c;于是在看 GPUImage 的源碼。其實有一定了解的伙伴一定知道 GPUImage 是通過 addTarget 鏈條的形式添加每一個環節。在對于這樣的設計贊嘆之余&#xff0c;想到了實際開發場景下可以用到的場景&#xff0c;借此分享。 我們的項目中應該有很…

馬爾科夫鏈蒙特卡洛_蒙特卡洛·馬可夫鏈

馬爾科夫鏈蒙特卡洛A Monte Carlo Markov Chain (MCMC) is a model describing a sequence of possible events where the probability of each event depends only on the state attained in the previous event. MCMC have a wide array of applications, the most common of…