UIColor
有颜色方法,例如blackColor
,whiteColor
等。我想得到一个颜色列表,如:['blackColor','whiteColor'...]
。但在检查method_list
,ivar_list
和property_list
后,我发现列表中没有颜色方法。代码用Swift
编写如下:
//: Playground - noun: a place where people can play
import UIKit
var ivarCount: UInt32 = 0
var propertyCount: UInt32 = 0
var methodCount: UInt32 = 0
let ivars = class_copyIvarList(UIColor.self, &ivarCount)
let properties = class_copyPropertyList(UIColor.self, &propertyCount)
let methods = class_copyMethodList(UIColor.self, &methodCount)
var ivarNames: [String] = []
var propertyNames: [String] = []
var methodNames: [String] = []
for var i = 0; i < Int(ivarCount); ++i {
let ivar = ivars[i]
let name = ivar_getName(ivar)
ivarNames.append(String.fromCString(name)!);
}
for var i = 0; i < Int(propertyCount); ++i {
let p = properties[i]
let name = property_getName(p)
propertyNames.append(String.fromCString(name)!)
}
for var i = 0; i < Int(methodCount); ++i {
let m = methods[i]
let name = sel_getName(method_getName(m))
methodNames.append(String.fromCString(name)!)
}
NSLog("ivars:%@",ivarNames)
NSLog("properties:%@", propertyNames)
NSLog("methods:%@", methodNames)
结果如下:
2016-01-18 11:26:25.531 MyPlayground[42239:4975071] ivar:(
"_systemColorName"
)
2016-01-18 11:26:25.531 MyPlayground[42239:4975071] properties:(
CGColor,
CIColor,
systemColorName
)
2016-01-18 11:26:25.532 MyPlayground[42239:4975071] method:(
"initWithColorLiteralRed:green:blue:alpha:",
classForCoder,
hash,
"isEqual:",
set,
"initWithHue:saturation:brightness:alpha:",
"_getWhite:alpha:",
"_systemColorName",
"initWithWhite:alpha:",
"_getRed:green:blue:alpha:",
"_colorBlendedWithColor:",
styleString,
isPatternColor,
"getHue:saturation:brightness:alpha:",
CIColor,
"initWithPatternImage:",
"_setSystemColorName:",
"_luminance",
"_colorBlendedWithColor:compositingFilter:",
"_isSimilarToColor:withinPercentage:",
"_colorDifferenceFromColor:",
"_luminanceDifferenceFromColor:",
"_colorBlendedWithColors:",
dealloc,
"copyWithZone:",
"encodeWithCoder:",
"initWithCoder:",
cgColor,
"initWithCGColor:",
"initWithRed:green:blue:alpha:",
CGColor,
"getRed:green:blue:alpha:",
setFill,
"colorWithAlphaComponent:",
setStroke,
alphaComponent,
"getWhite:alpha:",
"initWithCIColor:"
)
答案 0 :(得分:2)
那是因为颜色方法是类方法,它们绑定到UIColor
的元类。并且class_copyMethodList
返回作为参数传递的类的实例方法。
您可以通过object_getClass()
调用UIColor
来获取元类,因此您只需更改一行即可获得UIColor
的所有类方法:
let methods = class_copyMethodList(object_getClass(UIColor.self), &methodCount)
object_getClass()
适用于Class
值,因为Objective-C
每个类都有一个isa
指针,这使得它有资格成为一个对象。