Skip to content

Commit

Permalink
Weakify all self references in closures
Browse files Browse the repository at this point in the history
  • Loading branch information
DJBen committed Apr 10, 2018
1 parent bf74914 commit 6364ee3
Show file tree
Hide file tree
Showing 16 changed files with 78 additions and 76 deletions.
10 changes: 5 additions & 5 deletions Graviton/Common/Managers/CelestialBodyObserverInfoManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ final class CelestialBodyObserverInfoManager: LocationSensitiveSubscriptionManag
if isFetching { return }
isFetching = true
let site = ObserverSite(naif: .majorBody(.earth), location: LocationManager.default.content ?? CLLocation())
Horizons.shared.fetchCelestialBodyObserverInfo(preferredDate: requestedJd.date, observerSite: site, mode: mode ?? CelestialBodyObserverInfoManager.globalMode, update: { (dict) in
self.content = dict
for (_, sub) in self.subscriptions {
Horizons.shared.fetchCelestialBodyObserverInfo(preferredDate: requestedJd.date, observerSite: site, mode: mode ?? CelestialBodyObserverInfoManager.globalMode, update: { [weak self] (dict) in
self?.content = dict
for (_, sub) in self!.subscriptions {
DispatchQueue.main.async {
sub.didLoad!(dict)
}
}
}, complete: { (_, _) in
self.isFetching = false
}, complete: { [weak self] (_, _) in
self!.isFetching = false
})
}

Expand Down
4 changes: 2 additions & 2 deletions Graviton/Common/Managers/LocationAndTimeManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ class ObserverLocationTimeManager: NSObject {

override init() {
super.init()
subId = LocationManager.default.subscribe(didUpdate: { (location) in
self.observerInfo = ObserverLocationTime(location: location, timestamp: self.julianDay ?? JulianDay.now)
subId = LocationManager.default.subscribe(didUpdate: { [weak self] (location) in
self?.observerInfo = ObserverLocationTime(location: location, timestamp: self!.julianDay ?? JulianDay.now)
})
}

Expand Down
4 changes: 2 additions & 2 deletions Graviton/Common/Managers/LocationManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class LocationManager: LiteSubscriptionManager<CLLocation>, CLLocationManagerDel
didSet {
if let loc = content {
updateAllSubscribers(loc)
LocationManager.decodeTimeZone(location: loc) { (timeZone) in
self.timeZone = timeZone
LocationManager.decodeTimeZone(location: loc) { [weak self] (timeZone) in
self?.timeZone = timeZone
}
} else {
self.timeZone = TimeZone.current
Expand Down
4 changes: 2 additions & 2 deletions Graviton/Common/Managers/MotionManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ class MotionManager: NSObject {

func startMotionUpdate() {
if motionManager.isDeviceMotionActive == false {
motionManager.startDeviceMotionUpdates(using: .xTrueNorthZVertical, to: queue) { (motion, error) in
motionManager.startDeviceMotionUpdates(using: .xTrueNorthZVertical, to: queue) { [weak self] (motion, error) in
if let error = error as? CMError {
if error == CMErrorTrueNorthNotAvailable {
// ignore
Expand All @@ -73,7 +73,7 @@ class MotionManager: NSObject {
}
if let motion = motion {
DispatchQueue.main.async {
self.subscriptions.forEach { (_, subscription) in
self!.subscriptions.forEach { (_, subscription) in
subscription.didUpdate?(motion)
}
}
Expand Down
10 changes: 5 additions & 5 deletions Graviton/Common/Managers/RiseTransitSetManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ final class RiseTransitSetManager: LocationSensitiveSubscriptionManager<[Naif: R
if isFetching { return }
isFetching = true
let site = ObserverSite(naif: .majorBody(.earth), location: LocationManager.default.content ?? CLLocation())
Horizons.shared.fetchRiseTransitSetElevation(preferredDate: requestedJd.date, observerSite: site, mode: mode ?? RiseTransitSetManager.globalMode, update: { (dict) in
self.content = dict
for (_, sub) in self.subscriptions {
Horizons.shared.fetchRiseTransitSetElevation(preferredDate: requestedJd.date, observerSite: site, mode: mode ?? RiseTransitSetManager.globalMode, update: { [weak self] (dict) in
self!.content = dict
for (_, sub) in self!.subscriptions {
DispatchQueue.main.async {
sub.didLoad!(dict)
}
}
}, complete: { (_, _) in
self.isFetching = false
}, complete: { [weak self] (_, _) in
self!.isFetching = false
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ class RealtimeInfoViewController: BaseTableViewController {
self.clearsSelectionOnViewWillAppear = false
let displayLink = CADisplayLink(target: self, selector: #selector(screenUpdate))
displayLink.add(to: .main, forMode: .defaultRunLoopMode)
locationSubscriptionId = LocationManager.default.subscribe { (_) in
self.tableView.reloadData()
locationSubscriptionId = LocationManager.default.subscribe { [weak self] (_) in
self?.tableView.reloadData()
}
}

Expand Down Expand Up @@ -89,12 +89,12 @@ class RealtimeInfoViewController: BaseTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)!
let actionController = UIAlertController(title: cell.textLabel?.text, message: cell.detailTextLabel?.text, preferredStyle: .actionSheet)
actionController.addAction(UIAlertAction(title: "Copy to clipboard", style: .default, handler: { (_) in
actionController.addAction(UIAlertAction(title: "Copy to clipboard", style: .default, handler: { [weak self] (_) in
UIPasteboard.general.string = cell.detailTextLabel?.text
self.tableView.deselectRow(at: indexPath, animated: true)
self?.tableView.deselectRow(at: indexPath, animated: true)
}))
actionController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) in
self.tableView.deselectRow(at: indexPath, animated: true)
actionController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { [weak self] (_) in
self?.tableView.deselectRow(at: indexPath, animated: true)
}))
present(actionController, animated: true, completion: nil)
}
Expand Down
10 changes: 5 additions & 5 deletions Graviton/Observer/Nodes/BooleanFlaggedLight.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,14 @@ class BooleanFlaggedLight: SCNLight, ObserverSceneElement {
self.onConfig = onConfig
self.offConfig = offConfig
super.init()
subscribe(setting: setting) { (_, shouldShow) in
subscribe(setting: setting) { [weak self] (_, shouldShow) in
if shouldShow {
if self.isSetUp == false {
self.setUpElement()
if self?.isSetUp == false {
self?.setUpElement()
}
self.showElement()
self?.showElement()
} else {
self.hideElement()
self?.hideElement()
}
}
setUpElement()
Expand Down
10 changes: 5 additions & 5 deletions Graviton/Observer/Nodes/BooleanFlaggedNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ class BooleanFlaggedNode: SCNNode, ObserverSceneElement {

init(setting: Settings.BooleanSetting) {
super.init()
subscribe(setting: setting) { (_, shouldShow) in
subscribe(setting: setting) { [weak self] (_, shouldShow) in
if shouldShow {
if self.isSetUp == false {
self.setUpElement()
if self?.isSetUp == false {
self?.setUpElement()
}
self.showElement()
self?.showElement()
} else {
self.hideElement()
self?.hideElement()
}
}
setUpElement()
Expand Down
20 changes: 10 additions & 10 deletions Graviton/Observer/Nodes/TimeWarpVerticalBar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,24 @@ class TimeWarpVerticalBar: SKNode {
super.init()
addChild(barNode)
addChild(emitter)
warpSubId = Timekeeper.default.subscribe(didUpdate: { (_) in
warpSubId = Timekeeper.default.subscribe(didUpdate: { [weak self] (_) in
let recentWarpSpeed = Timekeeper.default.recentWarpSpeed
if recentWarpSpeed == 0 {
self.emitter.particleBirthRate = 0
self.emitter.particleSpeed = 0
self?.emitter.particleBirthRate = 0
self?.emitter.particleSpeed = 0
return
} else if recentWarpSpeed < 0 {
self.emitter.emissionAngle = -CGFloat.pi / 2
self.emitter.position = CGPoint(x: 0, y: -2)
self?.emitter.emissionAngle = -CGFloat.pi / 2
self?.emitter.position = CGPoint(x: 0, y: -2)
} else {
self.emitter.emissionAngle = CGFloat.pi / 2
self.emitter.position = CGPoint(x: 0, y: 2)
self?.emitter.emissionAngle = CGFloat.pi / 2
self?.emitter.position = CGPoint(x: 0, y: 2)
}
let interp = Easing(easingMethod: .quadraticEaseOut, startValue: 0, endValue: 250)
let percentage = abs(recentWarpSpeed > 0 ? log(recentWarpSpeed) : -log(-recentWarpSpeed)).cap(toRange: 0..<15) / 15
self.emitter.particleSpeed = CGFloat(interp.value(at: percentage))
self.emitter.particleSpeedRange = CGFloat(interp.value(at: percentage) / 10)
self.emitter.particleBirthRate = CGFloat(interp.value(at: percentage) * 1.5)
self?.emitter.particleSpeed = CGFloat(interp.value(at: percentage))
self?.emitter.particleSpeedRange = CGFloat(interp.value(at: percentage) / 10)
self?.emitter.particleBirthRate = CGFloat(interp.value(at: percentage) * 1.5)
})
}

Expand Down
12 changes: 6 additions & 6 deletions Graviton/Observer/Scenes/ObserverScene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,26 +257,26 @@ class ObserverScene: SCNScene, CameraResponsive, FocusingSupport {
rootNode.addChildNode(focuser)
focuser.isHidden = true

jumpToCelestialPointObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "jumpToCelestialPoint"), object: nil, queue: OperationQueue.main) { (notification) in
jumpToCelestialPointObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "jumpToCelestialPoint"), object: nil, queue: OperationQueue.main) { [weak self] (notification) in
guard let coordinate = notification.userInfo?["content"] as? EquatorialCoordinate else {
return
}
self.cameraNode.orientation = SCNQuaternion(Quaternion(alignVector: Vector3(1, 0, 0), with: Vector3(equatorialCoordinate: coordinate)))
self?.cameraNode.orientation = SCNQuaternion(Quaternion(alignVector: Vector3(1, 0, 0), with: Vector3(equatorialCoordinate: coordinate)))
}
jumpToDirectionObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "jumpToDirection"), object: nil, queue: OperationQueue.main) { (notification) in
jumpToDirectionObserver = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "jumpToDirection"), object: nil, queue: OperationQueue.main) { [weak self] (notification) in
guard let coordinate = notification.userInfo?["content"] as? HorizontalCoordinate else {
return
}
guard let obInfo = ObserverLocationTimeManager.default.observerInfo else {
logger.error("Missing observer info")
return
}
self.cameraNode.orientation = SCNQuaternion(Quaternion(alignVector: Vector3(1, 0, 0), with: Vector3(equatorialCoordinate: EquatorialCoordinate(horizontalCoordinate: coordinate, observerInfo: obInfo))))
self?.cameraNode.orientation = SCNQuaternion(Quaternion(alignVector: Vector3(1, 0, 0), with: Vector3(equatorialCoordinate: EquatorialCoordinate(horizontalCoordinate: coordinate, observerInfo: obInfo))))
}

loadPanoramaTexture(Settings.default[.groundTexture])
Settings.default.subscribe(setting: .groundTexture, object: self) { (_, newValue) in
self.loadPanoramaTexture(newValue)
Settings.default.subscribe(setting: .groundTexture, object: self) { [weak self] (_, newValue) in
self?.loadPanoramaTexture(newValue)
}
}

Expand Down
22 changes: 11 additions & 11 deletions Graviton/Observer/ViewControllers/ObserverMenuController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,24 @@ class ObserverMenuController: ObserverTableViewController {
setUpBlurredBackground()

let behaviors = menu.registerAllConditionalDisabling()
behaviors.forEach { (behavior) in
let indexPath = self.menu.indexPath(for: behavior.setting)!
behaviors.forEach { [weak self] (behavior) in
let indexPath = self!.menu.indexPath(for: behavior.setting)!
if behavior.condition == Settings.default[behavior.dependent] {
self.indexPathsToDisable.insert(indexPath)
self!.indexPathsToDisable.insert(indexPath)
} else {
self.indexPathsToDisable.remove(indexPath)
self!.indexPathsToDisable.remove(indexPath)
}
Settings.default.subscribe(setting: behavior.dependent, object: self, valueChanged: { (_, newValue) in
Settings.default.subscribe(setting: behavior.dependent, object: self!, valueChanged: { [weak self] (_, newValue) in
if behavior.condition == newValue {
self.indexPathsToDisable.insert(indexPath)
self!.indexPathsToDisable.insert(indexPath)
} else {
self.indexPathsToDisable.remove(indexPath)
self!.indexPathsToDisable.remove(indexPath)
}
self.tableView.reloadRows(at: [indexPath], with: .automatic)
self!.tableView.reloadRows(at: [indexPath], with: .automatic)
})
Settings.default.subscribe(setting: behavior.setting, object: self, valueChanged: { (_, newValue) in
if let cell = self.tableView.cellForRow(at: indexPath) as? MenuToggleCell, cell.toggle.isEnabled == newValue {
self.tableView.reloadRows(at: [indexPath], with: .automatic)
Settings.default.subscribe(setting: behavior.setting, object: self!, valueChanged: { [weak self] (_, newValue) in
if let cell = self!.tableView.cellForRow(at: indexPath) as? MenuToggleCell, cell.toggle.isEnabled == newValue {
self!.tableView.reloadRows(at: [indexPath], with: .automatic)
}
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ class ObserverMenuMultipleSelectController: ObserverTableViewController {
setUpBlurredBackground()
title = multipleSelect.text
tableView.register(MenuCell.self, forCellReuseIdentifier: checkableCellId)
Settings.default.subscribe(settings: [.groundTexture, .antialiasingMode], object: self) { (_, _) in
self.tableView.reloadData()
Settings.default.subscribe(settings: [.groundTexture, .antialiasingMode], object: self) { [weak self] (_, _) in
self!.tableView.reloadData()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@ class ObserverViewController: SceneController {
super.viewWillAppear(animated)
updateTimeLabel()
updateAntialiasingMode(Settings.default[.antialiasingMode])
Settings.default.subscribe(setting: .antialiasingMode, object: self) { (_, newKey) in
self.updateAntialiasingMode(newKey)
Settings.default.subscribe(setting: .antialiasingMode, object: self) { [weak self] (_, newKey) in
self?.updateAntialiasingMode(newKey)
}
}

Expand Down
16 changes: 9 additions & 7 deletions Graviton/SolarSystem/Scenes/SolarSystemScene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class SolarSystemScene: SCNScene, CameraResponsive, FocusingSupport {
private static let minScale: Double = 0.02
private static let diminishStartDistance: Float = 3.3
private static let diminishEndDistance: Float = 1.8
private static let sunNodeSize: CGFloat = 0.9
private static let planetNodeSize: CGFloat = 0.7

var gestureOrientation: Quaternion {
return Quaternion.identity
Expand All @@ -41,8 +43,8 @@ class SolarSystemScene: SCNScene, CameraResponsive, FocusingSupport {

var julianDay: JulianDay = JulianDay.J2000 {
didSet {
orbitalMotions.forEach { (motion, color, identifier) in
self.drawOrbitalMotion(motion: motion, color: color, identifier: identifier)
orbitalMotions.forEach { [weak self] (motion, color, identifier) in
self?.drawOrbitalMotion(motion: motion, color: color, identifier: identifier)
}
}
}
Expand Down Expand Up @@ -81,8 +83,8 @@ class SolarSystemScene: SCNScene, CameraResponsive, FocusingSupport {
}()

private lazy var sunNode: SCNNode = {
let sun = SCNNode(geometry: SCNSphere(radius: 1.2))
sun.name = "10"
let sun = SCNNode(geometry: SCNSphere(radius: SolarSystemScene.sunNodeSize))
sun.name = String(Naif.sun.rawValue)
sun.geometry!.firstMaterial = {
let mat = SCNMaterial()
mat.emission.contents = UIColor.white
Expand Down Expand Up @@ -139,9 +141,9 @@ class SolarSystemScene: SCNScene, CameraResponsive, FocusingSupport {
899: #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1),
999: #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
]
ephemeris.forEach { (body) in
ephemeris.forEach { [weak self] (body) in
if let color = colors[body.naifId] {
self.add(body: body, color: color)
self?.add(body: body, color: color)
}
}
}
Expand Down Expand Up @@ -186,7 +188,7 @@ class SolarSystemScene: SCNScene, CameraResponsive, FocusingSupport {
if let planetNode = spheres.childNode(withName: String(identifier), recursively: false) {
planetNode.position = zoom(position: motion.position)
} else {
let sphere = SCNSphere(radius: 0.85)
let sphere = SCNSphere(radius: SolarSystemScene.planetNodeSize)
sphere.firstMaterial = {
let mat = SCNMaterial()
mat.diffuse.contents = color
Expand Down
4 changes: 2 additions & 2 deletions Orbits/Models/Ephemeris.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ public extension Ephemeris {
/// - maximumAngularDistance: Will ignore bodies with greater angular separation than this value.
/// - Returns: The closest body to a direction viewed from an observer
func closestBody(toUnitPosition unitPosition: Vector3, from observer: CelestialBody, maximumAngularDistance: RadianAngle = RadianAngle(Double.pi * 2)) -> CelestialBody? {
return self.map { (targetBody) -> (body: CelestialBody, separation: Double) in
let vec = self.observedPosition(of: targetBody, fromObserver: observer).normalized()
return self.map { [weak self] (targetBody) -> (body: CelestialBody, separation: Double) in
let vec = self!.observedPosition(of: targetBody, fromObserver: observer).normalized()
return (targetBody, unitPosition.angularSeparation(from: vec))
}.filter { (targetBody, separation) -> Bool in
return observer != targetBody && separation <= maximumAngularDistance.wrappedValue
Expand Down
Loading

0 comments on commit 6364ee3

Please sign in to comment.