在iOS中跳过/忽略方法

如何跳过iOS中的完整方法? 我知道如何testing一个方法的iOS版本,但不知道如何完全忽略一个方法。

具体的例子:iOS8添加了自定义表格视图单元格,并且不再需要方法heightForRowAtIndexPath:estimatedHeightForRowAtIndexPath: :。 但是我确实需要iOS7。 现在,当我逐步浏览iOS8中的代码时,即使不再需要,也会调用这两种方法。

提供基于iOS版本的不同代理。 这允许你将代码封装在有意义的命名块中(你的接口将指示它是iOS7),而且你不会做任何欺骗的respondsToSelector ,它可能会破坏你的类的子类,实际上想使用这些方法。

 @interface MyTableViewDelegate : NSObject <UITableViewDelegate> @end @interface MyTableViewDelegateiOS7 : MyTableViewDelegate - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath; @end @implementation YourClass : .. <..> // .. - (void)loadView { [super loadView]; if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedAscending) { self.tableView.delegate = [[MyTableViewDelegate alloc] init]; } else { self.tableView.delegate = [[MyTableViewDelegateiOS7 alloc] init]; } } @end 

你有一个UITableViewDelegate设置为UITableViewDelegate的委托,你想给不同版本的iOS提供不同的委托方法。

在调用[delegate tableView:self heightForRowAtIndexPath:indexPath]之前, UITableView将调用[delegate respondsToSelector:@selector(tableView:heightForRowAtIndexPath:)] [delegate tableView:self heightForRowAtIndexPath:indexPath]

这需要一个自定义的-respondsToSelector: 在你的UITableViewDelegate类中添加这个方法。

 - (BOOL)respondsToSelector:(SEL)aSelector { // If this device is running iOS 8 or greater. if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0" options:NSNumericSearch] != NSOrderedAscending) { if (aSelector == @selector(tableView:heightForRowAtIndexPath:)) return NO; if (aSelector == @selector(tableView:estimatedHeightForRowAtIndexPath:)) return NO; } return [super respondsToSelector:aSelector]; } 

更新:我修复了委托方法名称。 DUH!