Embedding a custom class in a subclass inheritance tree in Objective-C

I consider myself an experienced Objective-C programmer. I use apps for life and make full use of language features. This includes using the runtime to modify changes within an existing framework. A similar swizzling method and dynamic subclasses really show how much more versatile this language is than other object-oriented C code.

But recently, I have had some thoughts about the old function, which I still need to use from time to time, but has long been deprecated. This is a replacement for the old class_setSuperClass.

I often find myself a subclass of UIKit classes to extend them or slightly change my behavior. One example that I came across recently was a subclass UIScrollViewthat made some conditions for panGestureRecognizer. I did this by subclassing UIScrollViewand then performed gestureRecognizer:shouldBeRequiredToFailByGestureRecognizer:.

You had to do this because you are not allowed to change the scroll view gesture recognizer delegate (it will throw an exception at runtime), and you cannot create your own custom UIScrollView panGestureRecognizer.

Now it all worked out great. I changed all the applications UIScrollViewin my application to my newly created subclass, and everything worked as expected. But what about UITableViewand UICollectionViewwhich I also used throughout the application. What to do with them? As you know, both of these classes are inherited from UIScrollView, but not my custom subclass UIScrollView. So I found that I ended up writing the same code several times for each class that existed (and was used in the application) that I inherited from UIScrollView. Writing the same code several times is 1-2-3 no-go programmers. But in the end, I wrote my own subclass not only for UIScrollView, but also for UITableViewand UICollectionView.

, class_setSuperClass, "swizzle" , UITableView. class_setSuperClass([UITableView class], [MyScrollView class]), ( ) . UITableView UIScrollView. , [[UITableView alloc] init], MyScrollView, .

class_setSuperClass iOS 2.0! swizzling isa. .

, . ?

+4
1

, , , . , class_replaceMethod(). , .

+4

Source: https://habr.com/ru/post/1538153/


All Articles