面试题答案
一键面试实现思路
- 动态添加属性:通过
objc_setAssociatedObject
和objc_getAssociatedObject
函数来实现关联对象,从而为对象动态添加属性。 - 动态添加方法:使用
class_addMethod
函数在运行时动态为类添加方法,实现动态行为。 - 优化内存管理:在复用组件时,确保关联对象正确释放。可以通过在对象的
dealloc
方法中移除关联对象来避免内存泄漏。
代码示例
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
// 定义关联对象的key
static const char *kCustomPropertyKey = "kCustomPropertyKey";
@interface CustomView : UIView
@end
@implementation CustomView
// 动态添加属性的setter方法
- (void)setCustomProperty:(NSString *)customProperty {
objc_setAssociatedObject(self, kCustomPropertyKey, customProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
// 动态添加属性的getter方法
- (NSString *)customProperty {
return objc_getAssociatedObject(self, kCustomPropertyKey);
}
// 动态添加方法
void dynamicMethodIMP(id self, SEL _cmd) {
NSLog(@"Dynamic method called on %@", self);
}
+ (void)load {
// 动态添加方法
class_addMethod(self, @selector(dynamicMethod), (IMP)dynamicMethodIMP, "v@:");
}
- (void)dealloc {
// 移除关联对象,优化内存管理
objc_setAssociatedObject(self, kCustomPropertyKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
@interface ViewController : UIViewController
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
CustomView *customView = [[CustomView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];
customView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:customView];
// 设置动态属性
customView.customProperty = @"Custom Value";
NSLog(@"Custom property: %@", customView.customProperty);
// 调用动态方法
if ([customView respondsToSelector:@selector(dynamicMethod)]) {
[customView performSelector:@selector(dynamicMethod)];
}
}
@end
在上述代码中:
CustomView
类通过关联对象动态添加了customProperty
属性。- 在
+load
方法中使用class_addMethod
动态添加了dynamicMethod
方法。 - 在
dealloc
方法中移除了关联对象,优化了内存管理。 - 在
ViewController
中创建了CustomView
实例,并演示了动态属性的设置与获取,以及动态方法的调用。