面试题答案
一键面试1. 提取方法
将重复代码提取到一个单独的方法中,这样在需要获取和解析数据的地方直接调用该方法。
// 假设在ViewController中
@interface ViewController ()
// 声明方法
- (void)fetchAndParseData;
@end
@implementation ViewController
- (void)fetchAndParseData {
// 从服务器获取数据的代码,例如使用NSURLSession
NSURL *url = [NSURL URLWithString:@"http://example.com/api/data"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data &&!error) {
// 解析数据,例如使用JSONSerialization
NSError *parseError;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (json &&!parseError) {
// 处理解析后的数据
NSLog(@"Parsed data: %@", json);
}
}
}];
[task resume];
}
- (void)method1 {
// 其他代码
[self fetchAndParseData];
// 其他代码
}
- (void)method2 {
// 其他代码
[self fetchAndParseData];
// 其他代码
}
@end
2. 使用类方法
如果这个获取和解析数据的操作与类的实例无关,可以将其定义为类方法。
@interface DataFetcher : NSObject
// 类方法声明
+ (void)fetchAndParseData;
@end
@implementation DataFetcher
+ (void)fetchAndParseData {
NSURL *url = [NSURL URLWithString:@"http://example.com/api/data"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data &&!error) {
NSError *parseError;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (json &&!parseError) {
NSLog(@"Parsed data: %@", json);
}
}
}];
[task resume];
}
@end
// 在其他类中使用
@interface AnotherViewController : UIViewController
@end
@implementation AnotherViewController
- (void)viewDidLoad {
[super viewDidLoad];
[DataFetcher fetchAndParseData];
}
@end
3. 创建数据管理器类
创建一个专门的数据管理器类,将获取和解析数据的逻辑封装在其中,提供对外接口。
@interface DataManager : NSObject
// 实例方法声明
- (void)fetchAndParseData;
@end
@implementation DataManager
- (void)fetchAndParseData {
NSURL *url = [NSURL URLWithString:@"http://example.com/api/data"];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data &&!error) {
NSError *parseError;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (json &&!parseError) {
NSLog(@"Parsed data: %@", json);
}
}
}];
[task resume];
}
@end
// 在视图控制器中使用
@interface ViewController : UIViewController {
DataManager *dataManager;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dataManager = [[DataManager alloc] init];
}
- (void)methodWithDataFetch {
[dataManager fetchAndParseData];
}
@end