Objective-C靜態庫中含有category怎麼辦?

1、蘋果推薦的方法

找到 target,更改其 Other Linker Flags 爲: -all_load 或 -force_load
-force_load,後跟隨一個文件位置,可以更精確地加載所需文件。 簡單點說就是,Objective-C 的動態特性使得需要,爲鏈接器添加一個標籤(設置 Other Linker Flags 爲 -ObjC)來解決通過 Category
向類添加方法的問題。 但這個標籤 -ObjC 在 64 位 和 iOS 中有問題,需要使用 -all_load 或 -force_load。

缺點:會將所有的符號都導入進來,造成庫比較大。

2、我的方法

在category聲明的地方添加一個類,然後隨便實現一個方法,然後在target中調用這個category中類的方法。但是如果有很多category的話一個一個添加比較麻煩,所以呢,我直接定義了幾個宏來簡化操作。

宏定義如下:

//
//  FixCategoryBug.h
//  MainLib
//
//  Created by shaozg on 15/7/31.
//  Copyright (c) 2015年 shaozg. All rights reserved.
//

#ifndef MainLib_FixCategoryBug_h
#define MainLib_FixCategoryBug_h

#define __kw_to_string_1(x) #x
#define __kw_to_string(x)  __kw_to_string_1(x)

// 需要在有category的頭文件中調用,例如 KW_FIX_CATEGORY_BUG_H(NSString_Extented)
#define KW_FIX_CATEGORY_BUG_H(name) \
    @interface KW_FIX_CATEGORY_BUG_##name : NSObject \
        +(void)print; \
    @end 

// 需要在有category的源文件中調用,例如 KW_FIX_CATEGORY_BUG_M(NSString_Extented)
#define KW_FIX_CATEGORY_BUG_M(name) \
    @implementation KW_FIX_CATEGORY_BUG_##name \
        + (void)print { \
            NSLog(@"[Enable category %s]", __kw_to_string(name)); \
        } \
    @end \


// 在target中啓用這個宏,其實就是調用下category中定義的類的print方法。
#define KW_ENABLE_CATEGORY(name) [KW_FIX_CATEGORY_BUG_##name print]

#endif

NSString+Extented.h如下:

//
//  NSString+Extented.h
//  MainLib
//
//  Created by shaozg on 15/7/31.
//  Copyright (c) 2015年 shaozg. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "FixCategoryBug.h"

KW_FIX_CATEGORY_BUG_H(NSString_Extented)

@interface NSString (Extented)

- (NSString *)testCategory;

@end

NSString+Extented.m內如如下:

//
//  NSString+Extented.m
//  MainLib
//
//  Created by shaozg on 15/7/31.
//  Copyright (c) 2015年 shaozg. All rights reserved.
//

#import "NSString+Extented.h"

KW_FIX_CATEGORY_BUG_M(NSString_Extented)

@implementation NSString (Extented)

- (NSString *)testCategory {
    return self;
}
@end

需要調用category的其它target部分代碼如下:

#import "AppDelegate.h"
#import "MainLib.h"
#import "NSString+Extented.h"
#import "SubLib.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
//    ENABLE_CATEGORY(NSString);
    KW_ENABLE_CATEGORY(NSString_Extented);

    NSLog(@"不會出錯了吧? %@", [@"當然!" testCategory]);
    return YES;
}

優點:使用簡單,根本不用改編譯選項;也不會增加庫的體積。
缺點:沒有缺點

如果小夥伴們有更簡單的方法,請一定分享吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章