面试题答案
一键面试优化思路
- 使用字面量语法:Objective-C 的字面量语法简洁且高效,相比于传统的
NSArray
和NSDictionary
创建方式,它在编译期生成代码,减少运行时开销。 - 减少对象创建开销:由于自定义对象遵循
NSCopying
协议,在添加到集合时会进行复制操作。尽量在创建集合前对对象进行必要的预处理,避免不必要的复制。 - 内存管理:确保对象的生命周期管理得当,避免内存泄漏。在集合不再使用时,及时释放内存。
关键代码片段
假设自定义对象为 MyCustomObject
,它遵循 NSCopying
协议。
#import <Foundation/Foundation.h>
@interface MyCustomObject : NSObject <NSCopying>
@property (nonatomic, strong) NSString *name;
- (instancetype)initWithName:(NSString *)name;
@end
@implementation MyCustomObject
- (instancetype)initWithName:(NSString *)name {
self = [super init];
if (self) {
_name = name;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
MyCustomObject *copy = [[[self class] allocWithZone:zone] initWithName:self.name];
return copy;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 创建自定义对象
MyCustomObject *obj1 = [[MyCustomObject alloc] initWithName:@"Object1"];
MyCustomObject *obj2 = [[MyCustomObject alloc] initWithName:@"Object2"];
// 使用字面量语法创建数组
NSArray *array = @[obj1, obj2];
// 使用字面量语法创建字典
NSDictionary *dictionary = @{@"Key1": obj1, @"Key2": obj2};
}
return 0;
}
在上述代码中:
- 使用
@[]
字面量语法创建NSArray
,使用@{}
字面量语法创建NSDictionary
,这两种方式简洁高效。 - 在
MyCustomObject
类中实现了NSCopying
协议的copyWithZone:
方法,确保对象在复制时的正确性。
通过这种方式,可以在频繁创建包含大量自定义对象的集合时,有效利用Objective-C的字面量语法进行高效的集合创建,并通过优化思路减少内存开销、提高创建速度。