logo头像

星星給予仰望者光芒

Obj-C 動態取得 Class 屬性名稱 and 屬性質值

本文于 1582 天之前發表,文章内容可能已經過時。

  Objective-C 擴充 NSArray 實現動態取得類別屬性, 縮減程式碼使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#import "NSArray+Extension.h"
#import <objc/runtime.h> // 導入運行時文件
@implementation NSArray (Extension)

// 返回當前類別所有屬性
+ (instancetype)getProperties:(Class)cls{

// 取得當前類別所以屬性
unsigned int count; // 記錄屬性個數
objc_property_t *properties = class_copyPropertyList(cls, &count);
//
NSMutableArray *mArray = [NSMutableArray array];
for (int i = 0; i < count; i++) {

// An opaque type that represents an Objective-C declared property.
// objc_property_t 屬性類型
objc_property_t property = properties[i];
// 獲取屬性的名稱 C語言 字串
const char *cName = property_getName(property);
// 轉換為 Objective C 字串
NSString *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];

[mArray addObject:name];
}

return mArray.copy;
}
@end

使用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    for (int i = 0; i <= [datas count]; i++) {
//取得所有屬性 ,檢查屬性值使否空
NSArray *names = [NSArray getProperties:[datas[i] class]];// #import "NSArray+Extension.h" 使用分類(擴充)
for (NSString *name in names) {
// 取得Property的值
id propertyValue = [datas[i] valueForKey:name];
NSLog(@"checkJoinMemberAPIPostParameter \npropertyName: %@, propertyValue: %@", name, propertyValue);
if !(propertyValue) {
// 如果等於空 表示沒有值
}
}
}

// }

這種方式可以使用在, 如果你有許多欄位要判斷的時候

例如: 加入會員 Class 裡面屬性有 15 個, 每個都要填寫, 都得判斷是否有填寫,
如果一般寫法可能需要 15 個 if 去判斷是否有填寫, 但這樣的寫法只要一個 if