【发布时间】:2012-05-23 22:33:44
【问题描述】:
[self class] 返回被调用方法的实例的Class,但是有没有办法获取该方法定义的Class呢?假设 B 类扩展了 A,并且 b 是 B 的实例,我想要 A 中的方法返回 A 而不是 B,即使从 b 调用也是如此。
已编辑:
我试图创建一个具有 -(void)releaseProperties 方法的 NSObject 类别,该方法获取该类中定义的所有属性,并将非只读对象属性设置为 nil。
- (void)releaseProperties {
unsigned int c = 0;
objc_property_t *properties = class_copyPropertyList([self class], &c);
for(unsigned int i = 0; i < c; i++) {
objc_property_t property = properties[i];
NSString *propertyName = [NSString stringWithUTF8String:property_getName(property)];
NSString *propertyType = [NSString stringWithUTF8String:property_getAttributes(property)];
if([propertyType hasPrefix:@"T@"] // is an object
&& [propertyType rangeOfString:@",R,"].location == NSNotFound // not readonly
) {
[self setValue:nil forKey:propertyName];
NSLog(@"%@.%@ = %@", NSStringFromClass(cls), propertyName, [self valueForKey:propertyName]);
}
}
free(properties);
}
我想在 dealloc 方法中使用这个方法,但是 class_copyPropertyList([self class], &c) 不会返回定义在它的超类中的属性,所以 super-dealloc 链不能正常工作。因此,我不想传递 [self 类],而是传递正在调用特定 dealloc 方法的类。
【问题讨论】:
标签: objective-c ios reflection