Skip to content

Commit

Permalink
Change file structure to make it clear
Browse files Browse the repository at this point in the history
  • Loading branch information
olddonkey committed Jan 14, 2017
1 parent 26243c1 commit 8d566b3
Show file tree
Hide file tree
Showing 6 changed files with 146 additions and 9 deletions.
Binary file added DemoScreenShot.jpeg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 15 additions & 4 deletions ODUIThreadGuard.xcodeproj/project.pbxproj
Expand Up @@ -14,7 +14,7 @@
A20D35191E0CFD9E00E6F975 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A20D35171E0CFD9E00E6F975 /* LaunchScreen.storyboard */; };
A20D35241E0CFD9F00E6F975 /* ODUIThreadGuardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20D35231E0CFD9F00E6F975 /* ODUIThreadGuardTests.swift */; };
A20D352F1E0CFD9F00E6F975 /* ODUIThreadGuardUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20D352E1E0CFD9F00E6F975 /* ODUIThreadGuardUITests.swift */; };
A20D353D1E0CFE3000E6F975 /* ODUIThreadGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = A20D353C1E0CFE3000E6F975 /* ODUIThreadGuard.swift */; };
A2E1E30C1E2A897F00EF4C85 /* ODUIThreadGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2E1E30B1E2A897F00EF4C85 /* ODUIThreadGuard.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -48,7 +48,7 @@
A20D352A1E0CFD9F00E6F975 /* ODUIThreadGuardUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = ODUIThreadGuardUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
A20D352E1E0CFD9F00E6F975 /* ODUIThreadGuardUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ODUIThreadGuardUITests.swift; sourceTree = "<group>"; };
A20D35301E0CFD9F00E6F975 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
A20D353C1E0CFE3000E6F975 /* ODUIThreadGuard.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ODUIThreadGuard.swift; sourceTree = "<group>"; };
A2E1E30B1E2A897F00EF4C85 /* ODUIThreadGuard.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ODUIThreadGuard.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -99,13 +99,13 @@
A20D350D1E0CFD9E00E6F975 /* ODUIThreadGuard */ = {
isa = PBXGroup;
children = (
A2E1E3081E2A86D500EF4C85 /* Sources */,
A20D350E1E0CFD9E00E6F975 /* AppDelegate.swift */,
A20D35101E0CFD9E00E6F975 /* ViewController.swift */,
A20D35121E0CFD9E00E6F975 /* Main.storyboard */,
A20D35151E0CFD9E00E6F975 /* Assets.xcassets */,
A20D35171E0CFD9E00E6F975 /* LaunchScreen.storyboard */,
A20D351A1E0CFD9E00E6F975 /* Info.plist */,
A20D353C1E0CFE3000E6F975 /* ODUIThreadGuard.swift */,
);
path = ODUIThreadGuard;
sourceTree = "<group>";
Expand All @@ -128,6 +128,14 @@
path = ODUIThreadGuardUITests;
sourceTree = "<group>";
};
A2E1E3081E2A86D500EF4C85 /* Sources */ = {
isa = PBXGroup;
children = (
A2E1E30B1E2A897F00EF4C85 /* ODUIThreadGuard.swift */,
);
name = Sources;
sourceTree = "<group>";
};
/* End PBXGroup section */

/* Begin PBXNativeTarget section */
Expand Down Expand Up @@ -267,7 +275,7 @@
files = (
A20D35111E0CFD9E00E6F975 /* ViewController.swift in Sources */,
A20D350F1E0CFD9E00E6F975 /* AppDelegate.swift in Sources */,
A20D353D1E0CFE3000E6F975 /* ODUIThreadGuard.swift in Sources */,
A2E1E30C1E2A897F00EF4C85 /* ODUIThreadGuard.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -518,6 +526,7 @@
A20D35351E0CFD9F00E6F975 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A20D35361E0CFD9F00E6F975 /* Build configuration list for PBXNativeTarget "ODUIThreadGuardTests" */ = {
isa = XCConfigurationList;
Expand All @@ -526,6 +535,7 @@
A20D35381E0CFD9F00E6F975 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
A20D35391E0CFD9F00E6F975 /* Build configuration list for PBXNativeTarget "ODUIThreadGuardUITests" */ = {
isa = XCConfigurationList;
Expand All @@ -534,6 +544,7 @@
A20D353B1E0CFD9F00E6F975 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
Expand Down
45 changes: 41 additions & 4 deletions ODUIThreadGuard/Base.lproj/Main.storyboard
@@ -1,23 +1,60 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11134" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11106"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="target" sceneMemberID="viewController">
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="ODUIThreadGuard" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="pP4-4E-Y3p">
<rect key="frame" x="121" y="385" width="132" height="30"/>
<state key="normal" title="Not on main thread"/>
<connections>
<action selector="runNotOnMainThread:" destination="BYZ-38-t0r" eventType="touchUpInside" id="oDu-Bx-mEt"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BNG-y7-QET">
<rect key="frame" x="134" y="455" width="106" height="30"/>
<state key="normal" title="On main thread"/>
<connections>
<action selector="runOnMainThread:" destination="BYZ-38-t0r" eventType="touchUpInside" id="C3v-Ab-Lh9"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="test label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="S7J-p9-UE7">
<rect key="frame" x="152" y="164" width="70" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="textColor"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="S7J-p9-UE7" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="1kj-hL-Kls"/>
<constraint firstItem="BNG-y7-QET" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="Nq6-aa-1xG"/>
<constraint firstItem="pP4-4E-Y3p" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="RHx-cT-tBS"/>
<constraint firstItem="pP4-4E-Y3p" firstAttribute="top" secondItem="S7J-p9-UE7" secondAttribute="bottom" constant="200" id="ahb-t6-JGH"/>
<constraint firstItem="BNG-y7-QET" firstAttribute="top" secondItem="pP4-4E-Y3p" secondAttribute="bottom" constant="40" id="jw2-0l-9fJ"/>
<constraint firstItem="S7J-p9-UE7" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" constant="-159" id="nnH-OS-fXZ"/>
</constraints>
</view>
<connections>
<outlet property="testLabel" destination="S7J-p9-UE7" id="nPh-V1-ta4"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
Expand Down
2 changes: 1 addition & 1 deletion ODUIThreadGuard/ODUIThreadGuard.swift
Expand Up @@ -15,7 +15,7 @@
import UIKit

/// It is better to use a debug flag here for not add this extension to Release build. (You don't want user see App crash)
#if debug
#if DEBUG
private let swizzle: (String, String, UIView.Type) -> Void = { (originalMethod, swizzledMethod, view) in
let originalSelector = Selector(originalMethod)
let swizzledSelector = Selector(swizzledMethod)
Expand Down
14 changes: 14 additions & 0 deletions ODUIThreadGuard/ViewController.swift
Expand Up @@ -10,10 +10,24 @@ import UIKit

class ViewController: UIViewController {

@IBOutlet weak var testLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

@IBAction func runNotOnMainThread(_ sender: Any) {
DispatchQueue.global().async {
self.testLabel.text = "Not on main thread"
}
}

@IBAction func runOnMainThread(_ sender: Any) {
DispatchQueue.main.async {
self.testLabel.text = "On main thread"
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
Expand Down
75 changes: 75 additions & 0 deletions Sources/ODUIThreadGuard.swift
@@ -0,0 +1,75 @@
//
// ODUIThreadGuard.swift
// ODUIThreadGuard
//
// Created by olddonkey on 2016/12/23.
// Copyright © 2016年 Old Donkey. All rights reserved.
//
// Based on the idea of https://gist.github.com/steipete/5664345
// MIT license
// Copyright © {olddonkey}
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import UIKit

/// It is better to use a debug flag here for not add this extension to Release build. (You don't want user see App crash)
#if debug
private let swizzle: (String, String, UIView.Type) -> Void = { (originalMethod, swizzledMethod, view) in
let originalSelector = Selector(originalMethod)
let swizzledSelector = Selector(swizzledMethod)

let originalMethod = class_getInstanceMethod(view, originalSelector)
let swizzledMethod = class_getInstanceMethod(view, swizzledSelector)

let didAddMethod = class_addMethod(view, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

if didAddMethod {
class_replaceMethod(view, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
} else {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}

// MARK: - A extension of UIView, basic idea is use runtime to exchange setNeedsLayout, setNeedsDisplay and setNeedsDisplayInRect with our customized method, and do the checking process in that method
extension UIView{
open override class func initialize() {
//If self is the subclass of UIView, return
if self !== UIView.self {
return
}

let methods = [
"setNeedsLayout": "guardSetNeedsLayout",
"setNeedsDisplay": "guardSetNeedsDisplay",
"setNeedsDisplayInRect:": "guardSetNeedsDisplayInRect:"
]

methods.forEach {(key, value) in
swizzle(key, value, self)
}
}

func guardSetNeedsLayout() {
checkThread()
guardSetNeedsLayout()
}

func guardSetNeedsDisplay() {
checkThread()
guardSetNeedsDisplay()
}

func guardSetNeedsDisplayInRect(_ rect: CGRect) {
checkThread()
guardSetNeedsDisplayInRect(rect)
}
//If not on main thread, assert the app. From the left side thread stack view, you can easily find which line has problem
func checkThread() {
assert(Thread.isMainThread, "You changed UI element not on main thread")
}

}
#endif

0 comments on commit 8d566b3

Please sign in to comment.