werediver / StyleSheet

Reusable and composable UI styles
MIT License
23 stars 3 forks source link

Why is all these swizzling safe? #2

Closed nikita-leonov closed 7 years ago

nikita-leonov commented 7 years ago

Having a documented explanation of things happening in RootStyle.swift especially implications of swizzleInstance(View.self, originalSelector: ViewDidMoveToWindowSelector, swizzledSelector: #selector(View.__stylesheet_didMoveToWindow)) should improve adoption of the framework. It seems very risky to have such a significant inference all around the app with such an important life-cycle methods such as didMoveToWindow etc. People need to know it is safe.

werediver commented 7 years ago

So, you are concerned about safety of the default automatic style application method.

What can be done?

1. Alternative method

For iOS and tvOS platforms there is an alternative automatic style application method based on the standard UIAppearance mechanism. It is as safe as UIAppearance is.

RootStyle.autoapply(style: style, mode: .appearance)

2. Manual application

This framework does not enforce the use of automatic style application. You can define your stylesheets using the framework and apply them manually as it's convenient for you.

Just don't call RootStyle.autoapply().

3. Use with caution

Method swizzling is a legitimate part of Objective-C Runtime API and is applicable to UIKit. There are a number of ways to swizzle methods and either will work even if a method is swizzled multiple times until some fragile swizzle-sensitive code is involved. There is a pretty famous question on StackOverflow on this topic (pay attention to the conclusion in the answer): What are the Dangers of Method Swizzling in Objective C?

Practice shows that the default automatic style application method is safe, fast, and convenient.

And you have a fallback just in case.

(this may be included into the project as a part of its documentation later)