iOS runtime 給 Category 加屬性

weixin_34041003發表於2016-12-03

首先建立一個 Model 類

#import <Foundation/Foundation.h>
@interface Model : NSObject

@end

新增 Category
標頭檔案


#import "Model.h"

@interface Model (Data)

@property (nonatomic,copy) NSString *data;

@end

m檔案


#import "Model+Data.h"
#import <objc/runtime.h>

NSString *const kData = @"data";
@implementation Model (Data)

- (NSString *)data{
    return objc_getAssociatedObject(self, (__bridge const void *)(kData));
}

- (void)setData:(NSString *)data{
    objc_setAssociatedObject(self, (__bridge const void *)(kData), data, OBJC_ASSOCIATION_COPY);
}

測試


#import <XCTest/XCTest.h>
#import "Model.h"
#import "Model+Data.h"

@interface TestRunTimerTests : XCTestCase
{
    Model *model ;
}
@end

@implementation TestRunTimerTests

- (void)setUp {
    [super setUp];
    model = [Model new];
}

- (void)testCartygor1{
    
    model.data = @"ddddd";
    NSLog(@"%@",model.data);
    NSAssert([model.data isEqualToString:@"ddddd"], @"fail--------");
}

- (void)testCartygor2 {
    
    
    NSLog(@"---- - =%@= ---",model.data);
    NSAssert(true, @"fail--------");
}

相關文章