日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

iOS 扩展机制category与associative

發布時間:2023/12/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 iOS 扩展机制category与associative 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

category和associative作為objective-c 擴展機制的兩個特性,category可以通過它來擴展方法;associative可以通過它來擴展屬性。

在iOS開發過程中,前者category比較常見,也比較簡單,這里就不說了,這里主要說一下associative;

后者associative相對用的就比較少,要用associative就必須使用#import<objc/runtime.h>,然后調用objc_setAssociatedObject 和?objc_getAssociatedObject ?方法分別為屬性添加setter 和 ?getter方法,就可以實現屬性擴展了。


下面介紹一下這兩個方法:

①:void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)

其中的參數分別是:

Parameters

object: ?The source object for the association.

key: The key for the association.

value: ?The value to associate with the key key for object. Pass nil to clear an existing association.

policy: ?The policy for the association

其中的policy有

enum {

?? OBJC_ASSOCIATION_ASSIGN = 0,

?? OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,

?? OBJC_ASSOCIATION_COPY_NONATOMIC = 3,

?? OBJC_ASSOCIATION_RETAIN = 01401,

?? OBJC_ASSOCIATION_COPY = 01403

};

②:id objc_getAssociatedObject(id object, void *key)

Parameters

object: ?The source object for the association.

key: ?The key for the association.

Return Value

The value associated with the key key for object.


都比較簡單,下面就通過一個demo來說明吧!

我這里是擴展UIImageview為其添加一個方法和一個屬性。

category的頭文件:

[cpp] view plaincopy
  • #import?<UIKit/UIKit.h>??
  • ??
  • @interface?UIImageView?(associate)??
  • ??
  • @property(nonatomic,strong)NSString*?myString;??
  • ??
  • -(void)Output;??
  • ??
  • @end??


  • category的實現文件:

    [cpp] view plaincopy
  • #import?<objc/runtime.h>??
  • #import?"UIImageView+associate.h"??
  • ??
  • static?void?*?MyKey?=?(void?*)@"MyKey";??
  • ??
  • @implementation?UIImageView?(associate)??
  • ??
  • -(NSString*)myString?{??
  • ????return?objc_getAssociatedObject(self,?MyKey);??
  • }??
  • ??
  • -(void)setMyString:(NSString?*)string?{??
  • ????objc_setAssociatedObject(self,?MyKey,?string,?OBJC_ASSOCIATION_COPY_NONATOMIC);??
  • }??
  • ??
  • -(void)Output?{??
  • ????NSLog(@"output?mystring:%@",self.myString);??
  • }??
  • @end??
  • ??
  • ??????

  • 說明:頭文件中添加了一個屬性和一個方法,在實現文件中使用associative特性為屬性重寫了setter和getter方法,都比較簡單。

    測試一下:

    [cpp] view plaincopy
  • UIImageView?*imageView?=?[[UIImageView?alloc]?initWithImage:[UIImage?imageNamed:@"Icon@2x.png"]];??
  • ????imageView.bounds?=?CGRectMake(50,?50,?100,?100);??
  • ????imageView.myString?=?@"hello?world";??
  • ????[self.view?addSubview:imageView];??????
  • ????[imageView?Output];??

  • 運行后,模擬器上就顯示一個圖片,終端輸出:output mystring:hello world

    總結

    以上是生活随笔為你收集整理的iOS 扩展机制category与associative的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。