涉及到的知識點
- 獲取一個model類的所有property列表
- 獲取這些property的類名
- NSString的排序使用
- 數組的排序使用方式
實例描述
將后臺發來的json entity轉譯成一個model類。將所有的類名和類對應的值組成一個長的字符串,所有的property變成字符串,并按自然順序排列。然后組成一個長字符串如:"key1=value1&key2=value2&...."
這里略去 JSON -> Model class的流程
NSString的排序
- 比較的方法:
[value compare:(NSString *)];
[value compare:(NSString *) options:(NSStringCompareOptions)];
[value compare:(NSString *) options:(NSStringCompareOptions) range:(NSRange)];
- 傳入的參數:
compare:(NSString *)
傳入一個需要比較的字符串。
例如 [value compare:@"1234567890"],返回 NSOrderedSame。
options:(NSStringCompareOptions)
- 傳入 NSStringCompareOptions 枚舉的值
enum{
NSCaseInsensitiveSearch = 1,//不區分大小寫比較
NSLiteralSearch = 2,//區分大小寫比較
NSBackwardsSearch = 4,//從字符串末尾開始搜索
NSAnchoredSearch = 8,//搜索限制范圍的字符串
NSNumbericSearch = 64//按照字符串里的數字為依據,算出順序。例如 Foo2.txt < Foo7.txt < Foo25.txt
//以下定義高于 mac os 10.5 或者高于 iphone 2.0 可用
,
NSDiacriticInsensitiveSearch = 128,//忽略 "-" 符號的比較
NSWidthInsensitiveSearch = 256,//忽略字符串的長度,比較出結果
NSForcedOrderingSearch = 512//忽略不區分大小寫比較的選項,并強制返回 NSOrderedAscending 或者 NSOrderedDescending
//以下定義高于 iphone 3.2 可用
,
NSRegularExpressionSearch = 1024//只能應用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:... 方法。使用通用兼容的比較方法,如果設置此項,可以去掉 NSCaseInsensitiveSearch 和 NSAnchoredSearch
}
range:(NSRange)
比較字符串的范圍
結構變量:
location: 需要比較的字串起始位置(以0為起始)
length: 需要比較的字串長度返回值:
typedef enum _NSComparisonResult {
NSOrderedAscending = -1, // < 升序
NSOrderedSame, // = 等于
NSOrderedDescending // > 降序
} NSComparisonResult;
代碼
- 獲取model 的property名,存在一個數組里。使用
runtime
unsigned int count;// 記錄屬性個數
objc_property_t *properties = class_copyPropertyList([TestModel class], &count);
// 生成一個屬性名稱組成的數組
NSMutableArray *propertyNameArray = [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];
[propertyNameArray addObject:name];
}
NSLog(@"排序前的屬性列表 = %@",propertyNameArray);
- 使用比較器設定排列順序
NSComparator cmptr = ^(NSString *obj1, NSString *obj2){
return [obj1 compare:obj2 options:NSLiteralSearch];
};
NSArray *afterSort = [propertyNameArray sortedArrayUsingComparator:cmptr];
NSLog(@"排序后的屬性列表 = %@",afterSort);
打印出排序前后的日志對比:
2016-07-09 17:13:49.956 SortMyProperty[90373:4208586] 排序前的屬性列表 = (
accessToken,usrType,usrStatus,enabled,mrchNo,mrchName,storeNo,storeName,hasLogin,operatorName,transferChannel,canRemit,canIncome,canUpgrade,isSetSecurityQuestion,isSupportCashConsume,serverBankUpdTime,signData
)
2016-07-09 17:13:49.957 SortMyProperty[90373:4208586] 排序后的屬性列表 = (
accessToken,canIncome,canRemit,canUpgrade,enabled,hasLogin,isSetSecurityQuestion,isSupportCashConsume,mrchName,mrchNo,operatorName,serverBankUpdTime,signData,storeName,storeNo,transferChannel,usrStatus,usrType
)