• iOS之Category关联属性


    Objective-C

    /** 原文件 */
    // Person.h
    #import <Foundation/Foundation.h>
    
    @interface Person : NSObject
    @property (nonatomic, copy) NSString *name;
    @end
    
    
    
    // Person.m
    #import "Person.h"
    
    @implementation Person
    - (instancetype)init {
        if (self = [super init]) {
            _name = @"";
            
            NSLog(@"%@", [self class]); // Person
            NSLog(@"%@", [super class]); // Person
        }
        return self;
    }
    
    - (void)dealloc {
        NSLog(@"Call dealloc in Person.m");
    }
    @end
    
    /** Category文件*/
    // Person+Category.h
    #import "Person.h"
    
    @interface Person (Category)
    // 添加属性address
    @property (nonatomic, copy) NSString *address;
    @end
    
    
    // Person+Category.m
    #import "Person+Category.h"
    #import <objc/runtime.h>
    
    @implementation Person (Category)
    
    static void *addressKey = &addressKey;
    
    #pragma mark - OC 在Category关联属性
    - (void)setAddress:(NSString *)address {
        objc_setAssociatedObject(self, &addressKey, address, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }
    
    - (NSString *)address {
        return objc_getAssociatedObject(self, &addressKey);
    }
    
    /** 在category里面执行dealloc方法后,Person类文件里的dealloc会不执行 */
    - (void)dealloc {
        objc_removeAssociatedObjects(self);
        NSLog(@"remove associated");
    }
    @end
    
    
    // test
    #import "Person+Category.h"
    
    Person *p = [Person new];
    p.name = @"xiaoMing";
    p.address = @"gz";
    NSLog(@"name is: %@, address is: %@", p.name, p.address);
    

    Swift

    // .swift文件
    import Cocoa
    
    class Car {
        var name = ""
    }
    
    
    private var priceKey: Void?
    extension Car {
        /// car's price
        var price: Double? {
            get {
                return objc_getAssociatedObject(self, &priceKey) as? Double
            }
            set {
                    objc_setAssociatedObject(self, &priceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
    
    let c1 = Car()
    c1.name = "su"
    c1.price = 110000.1
    print("c1's name is: (c1.name) and price is: (c1.price!)")
    
    
    
  • 相关阅读:
    POJ 3923 Ugly Windows(——考察思维缜密性的模拟题)
    POJ 3829 Seat taking up is tough(——只是题目很长的模拟)
    练习json读取中文
    关于调接口和腾讯云cos方面。
    JavaScript如何处理解析JSON数据详解
    js获取url参数值的两种方式
    修改Host,配置域名访问
    Atom设置震撼的编辑效果
    atom总结
    用node.js可以开启静态服务 不需要借助apache 或者xampl
  • 原文地址:https://www.cnblogs.com/mustard22/p/11091283.html
Copyright © 2020-2023  润新知