Post

Replies

Boosts

Views

Activity

memory race on deep looper
Below is some simple code that does nothing, saves nothing. Yet the memory usage keeps rising. Am I missing something or is this a bug? The code requires 6 core CPU minimum. ContentView.swift import SwiftUI import Combine struct ContentView: View { @EnvironmentObject var loopClass:LoopClass var body: some View { ProgressView(value: Float(loopClass.loop_count), total: Float(loopClass.max_loops) ).progressViewStyle(.circular).padding() Button("Run looper", action: { loopClass.loopFunc() } ) } } LoopClass.swift import Combine class LoopClass: ObservableObject { @Published var loop_count = 0 @Published var max_loops = 0 func loopFunc () { let loopSet = [ 1, 3, 5, 7, 11, 13 ] max_loops = Int(pow(Double(loopSet.count), 13.0)) print("max_loops = \(max_loops)") for loop13 in loopSet { DispatchQueue.global().async { for loop12 in loopSet { for loop11 in loopSet { for loop10 in loopSet { for loop9 in loopSet { for loop8 in loopSet { for loop17 in loopSet { for loop16 in loopSet { for loop5 in loopSet { for loop4 in loopSet { for loop3 in loopSet { for loop2 in loopSet { for loop1 in loopSet { DispatchQueue.main.async{ self.loop_count += 1 } } }}}}}}}}}}} } // DQ } // for loop13 } }
2
0
962
Jul ’23
12 core M2 mini only using 4 cores, Intel Mac mini used 6
Developing a program that needs maximum cores. My previous Intel Mac mini used all 6 cores, according to Activity Monitor. It showed 600% cpu usage. I assumed the M2 would use twelve, but only shows 400% cpu usage in Activity Monitor, ergo, two less! I don't recall setting a core usage parameter in Xcode. Any ideas? Ventura 13.3 and Xcode 14.3 up to date as of this post.
2
0
944
May ’23
Delegation in Swift
This is the second issue in my post "ProgressBar with DispatchQueue", delegation. I have used delegates with menu items but not program vars. In the previous post my ViewController has a progress bar but I would like the progress.DoubleValue var to be updated in a remote function, i.e., a function not declared within the ViewController class. (If I moved the function into the ViewController it would double in size.) How do I create and implement such a delegate? Please give example code. Thanks.
5
0
1.2k
Jun ’22
EnvironmentObject as progressValue in ProgressView()
The model increments through a range of dates converted to Double and scaled, ranging from 0 to 1.0 I wish to show a determinate progress bar. As I understand it, the ProgressView() must be declared in the ContentView and its progress var must be declared as a @State var The ContentView declares the model vars as @EnvironmentObjects If I declare: @State private var = model.progressValue I get the error:"Cannot use instance member 'model' within property initializer; property initializers run before 'self' is available" btw the model class declares: @Published var progressValue : Double The model func (to increment through dates) is launched by a button in the ContentView. idk how to get the incremented progressValue from the model to the ContentView State var.
3
0
1.2k
Jun ’22
Is Core Data the right tool?
My app generates piecemeal near terabyte data distributed over one hundred files. Due to RAM and internal HD limitations I must store to an external HD in piecemeal fashion. That is to say, append fresh records directly to an existing file without reading-in the whole file, appending, and writing it out again. Ultimately (when data generation ceases) I will check each file to ensure uniqueness of member data structures. Is Core Data the tool I should use? If not, how do I append directly to disk-files without first reading it in?
5
0
1.3k
May ’22
format printed SIMD3's
I print a lot of SIMD3 vectors to the debugger area in Xcode. Some vector-elements have prefixed signs and some values are longer than others. I would like the printed vectors to align as they did in my old days of Fortran. The SIMD3 members are scalars which can't be cast as Double ( I know how to format output for Double) or even as NSNumber. Something akin to a NumberFormatter for vectors would be the objective, but I don't see how to do it. Scalars are wierd and (helpful) documentation sparse.
5
0
824
Jan ’22
Warning about truncatingRemainder
it may not deliver what you expect. For example: if you are using NASA/JPL/Standish equations of heliocentric planetary motion, it requires: "3. Modulus the mean anomaly (M) so that -180deg<=M<=+180deg and then obtain the eccentric anomaly, E, from the solution of Kepler's equation..." If you attempt to use the Swift "Modulo operator, %" you'll get the Xcode directive to use truncatingRemainder instead. Which IS better than % because of this note in "The Swift Programming Language (Swift 5.3)": "“NOTE The remainder operator (%) is also known as a modulo operator in other languages. However, its behavior in Swift for negative numbers means that, strictly speaking, it’s a remainder rather than a modulo operation.” Excerpt From The Swift Programming Language (Swift 5.3) Apple Inc. https://books.apple.com/us/book/the-swift-programming-language-swift-5-5/id881256329 This material may be protected by copyright. But you should try truncatingRemainder in your playground! Let: 0deg = 12 O'clock, 180/-180deg = 6 O'clock, -90deg = 9 O'clock and +90deg = 3 O'clock Now run this on your playground: let M = -181.25 var M180 = M while M180 > 180.0 { M180 -= 360.0 } while M180 < -180.0 { M180 += 360.0 } print("M = \(M)\t\tM180 = \(M180)\t\tM.truncatingRemainder(dividingBy: 180.0) = \(M.truncatingRemainder(dividingBy: 180.0))\t\tM.truncatingRemainder(dividingBy: 360.0) = \(M.truncatingRemainder(dividingBy: 360.0))") and you'll get this result: M = -181.25        M180 = 178.75 M.truncatingRemainder(dividingBy: 180.0) = -1.25 M.truncatingRemainder(dividingBy: 360.0) = -181.25 Thus, truncatingRemainder(dividingBy: 180.0) puts your planet 180deg away from where it should be, while M180 keeps the planets moving without quantum leaps.
0
0
825
Jan ’22
FYI: Playing a movie using AVPlayer in Big Sur
took a bit of experimenting... import AVKit    //  macOS & iOS class ViewController_myShow: NSViewController {          @IBOutlet var myMOV: AVPlayerView! 10.          override func viewDidLoad() {         super.viewDidLoad()                  let playerView = AVPlayerView() 20. 21.         playerView.translatesAutoresizingMaskIntoConstraints = false 22. 23.         view.addSubview(playerView) 24. 25. 26. 27.         playerView.leadingAnchor.constraint  (equalTo: view.safeAreaLayoutGuide.leadingAnchor ).isActive = true 28. 29.         playerView.trailingAnchor.constraint (equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true 30. 31.         playerView.topAnchor.constraint      (equalTo: view.safeAreaLayoutGuide.topAnchor     ).isActive = true 32. 33.         playerView.bottomAnchor.constraint   (equalTo: view.safeAreaLayoutGuide.bottomAnchor  ).isActive = true 34. 35. 36. 37.         playerView.controlsStyle = .floating 38. 39.         playerView.showsFrameSteppingButtons   = true 40. 41.         playerView.showsFullScreenToggleButton = true 42. 43.          44. 45.         guard let path = Bundle.main.url(forResource: "myMovie", withExtension: "mov") else { return } 46. 47. 48. 49.         let player = AVPlayer(url: path) 50. 51.             playerView.player = player 52. 53.         playerView.player?.play()   54. 55.     } 56. 57. } The StoryBoard:AttributesInspector:AVPlayerView settings don't work for me... exactly. I had to set StoryBoard:AttributesInspector:AVPlayerView:ControlsStyle:none then include lines 37-41 in my code. The default is StoryBoard:AttributesInspector:AVPlayerView:ControlsStyle:inline which appears on screen but does nothing, i.e., no control. Line 21 is also required to be false. The .mov file can be File:AddFilesTo 'd or copied to Assets.xcassets see also: Developer Forum: "can't get extremely simple macOS video player to work..." https://developer.apple.com/documentation/avfoundation/media_playback_and_selection/creating_a_basic_video_player_macos &#9;&#9;&#9;
1
0
1k
Jan ’22
ProgressBar with DispatchQueue
I have searched but cannot find an example of this. In my example I use playground to nest for-loops in a function called from within DispatchQueue. I find many roadblocks: //import AppKit // playground doesn't recognize AppKit?! import Dispatch import Foundation var comboCount:NSKeyValueObservation? //class viewContr: NSViewController { @IBOutlet weak var progressBar: NSProgressIndicator! // deinit { comboCount?.invalidate() } @IBAction func calcStuff() { DispatchQueue.global(qos: .userInitiated).async { let combos = possibleCombos() DispatchQueue.main.async { for word in combos { word.print0b8() } } } } //} func possibleCombos() -> [Int8] { var combos = [Int8]() for a in [0, 1] { for b in [0, 1] { for c in [0, 1] { for d in [0, 1] { combos.append(Int8(d | (c << 1) | (b << 2) | (a << 3)) ) comboCount = combos.count/16 as! NSKeyValueObservation // known total combos = 16 // How do I pass combos.count out to a progress bar? } } } } return combos } extension Int8 {func print0b8() {print("0b" + pad(string: String(self, radix: 2), toSize: 4))}} func pad(string : String, toSize: Int) -> String {var padded = string;for _ in 0..<(toSize - string.count) {padded = "0" + padded};return padded} Removing the @IB obstacles and the attempted declaration of a ViewController does produce output, but can't be used with a progress bar, e.g., import Dispatch import Foundation DispatchQueue.global(qos: .userInitiated).async { let combos = possibleCombos() DispatchQueue.main.async { for word in combos { word.print0b8() } } } func possibleCombos() -> [Int8] { var combos = [Int8]() for a in [0, 1] { for b in [0, 1] { for c in [0, 1] { for d in [0, 1] { combos.append(Int8(d | (c << 1) | (b << 2) | (a << 3)) ) // known total combos = 16 // How do I pass combos.count out to a progress bar? } } } } return combos } extension Int8 {func print0b8() {print("0b" + pad(string: String(self, radix: 2), toSize: 4))}} func pad(string : String, toSize: Int) -> String {var padded = string;for _ in 0..<(toSize - string.count) {padded = "0" + padded};return padded} In my actual App, i.e., not this playground, I have a ProgressBar in my storyboard and an IBoutlet declared in my view controller. I just can't find how to pass a value out of "possibleCombos()" and into the NSProgressIndicator. What I have read suggests a delegate but reading about delegates hasn't helped. I need an example. Thanks.
8
0
2.1k
Nov ’21
Missing Fundamental something
Code to draw a graph of data. Each abscissa has an ordinate range to be displayed as a line segment. All data, i.e., scaled points are verified to be within the declared analysisView.bounds. strokeColors are verified within the range 0..1 BTW, no I don't need animation for this static data, but CALayer seemed to require more coding, and I found fewer code examples for it. The code below has two problems: 1) it doesn't draw into the window the weird behavior of min/max The first is why I am posting. What am I missing? import AppKit class AnalysisViewController: NSViewController { @IBOutlet var analysisView: NSView! var ranges = [ClosedRange<Double>]() var ordinateMinimum = CGFloat() var ordinateMaximum = CGFloat() var ordinateScale = CGFloat() let abscissaMinimum:CGFloat = 1 let abscissaMaximum:CGFloat = 92 let abscissaScale :CGFloat = 800/92 let shapeLayer = CAShapeLayer() var points = [CGPoint]() // created just to verify (in debugger area) that points are within analysisView.bounds func genrateGraph() { // ranges.append(0...0) // inexplicably FAILS! @ ordinateMinimum/ordinateMaximum if replaces "if N == 1" below // ranges.append(0.1...0.1) // non-zero range does not fail but becomes the min or max, therefore, not useful for N in 1...92 { if let element = loadFromJSON(N) { if N == 1 { ranges.append( element.someFunction() ) } // ranges[0] is an unused placeholder // if N == 1 { ranges.append(0...0) } // inexplicably FAILS! @ ordinateMinimum/ordinateMaximum if replacing above line ranges.append( element.someFunction() ) } else { ranges.append(0...0) } // some elements have no range data } ordinateMinimum = CGFloat(ranges.min(by: {$0 != 0...0 && $1 != 0...0 && $0.lowerBound < $1.lowerBound})!.lowerBound) ordinateMaximum = CGFloat(ranges.max(by: {$0 != 0...0 && $1 != 0...0 && $0.upperBound < $1.upperBound})!.upperBound) ordinateScale = analysisView.frame.height/(ordinateMaximum - ordinateMinimum) for range in 1..<ranges.count { shapeLayer.addSublayer(CALayer()) // sublayer each abscissa range so that .strokeColor can be assigned to each // shapeLayer.frame = CGRect(x: 0, y: 0, width: analysisView.frame.width, height: analysisView.frame.height) // might be unneccessary let path = CGMutablePath() // a new path for every sublayer, i.e., range that is displayed as line segment points.append(CGPoint(x: CGFloat(range)*abscissaScale, y: CGFloat(ranges[range].lowerBound)*ordinateScale)) path.move(to: points.last! ) points.append(CGPoint(x: CGFloat(range)*abscissaScale, y: CGFloat(ranges[range].upperBound)*ordinateScale)) path.addLine(to: points.last! ) path.closeSubpath() shapeLayer.path = path // shapeLayer.strokeColor = CGColor.white let r:CGFloat = 1.0/CGFloat(range) let g:CGFloat = 0.3/CGFloat(range) let b:CGFloat = 0.7/CGFloat(range) // print("range: \(range)\tr: \(r)\tg: \(g)\tb: \(b)") // just to verify 0...1 values shapeLayer.strokeColor = CGColor(srgbRed: r, green: g, blue: b, alpha: 1.0) } } override func viewDidLoad() { super.viewDidLoad() view.wantsLayer = true // one of these (view or analysisView) must be unneccessary view.frame = CGRect(x: 0, y: 0, width: 840, height: 640) analysisView.wantsLayer = true analysisView.frame = CGRect(x: 0, y: 0, width: 840, height: 640) genrateGraph() } }
7
0
1.3k
Oct ’21
swift Process() return values
How do I access a returned value from a Process(), in this case 'which'... var sips_path : String? //MARK: locate sips on local machine let which_sips = Process() which_sips.executableURL = URL(fileURLWithPath: "which") which_sips.arguments = ["sips"] do { sips_path = try which_sips.run() } catch let error as NSError { sips_path = "/usr/bin/sips"; print("Failed to execute which_sips", error) }line 8. gets compiler error "Cannot assign value of type '()' to type 'String?'" I believe, but cannot prove, 'which' returns a string. .run() throws and throws are for errors only, right? So where is the result of calling which?It seems I should use a closure to use $0 but it's already in one...line 9. intends to assign a default path.
13
1
7.7k
Oct ’21
SceneKits future
I have developed an app using SceneKit since Swift came out. Now SwiftUI is out and uses structs rather than classes. SceneKit is a cascade of classes. As a newbie, I am concerned that my code might be obsolete through depreciations soon after publication and I'd rather get ahead of the issues now. So, is SceneKit long-term viable? My first attempts at converting my custom classes to structs seems impossible without Apple leading the way. If I understand correctly, I can make a struct whose only member is an instance of a class, but the benefits of the struct, e.g., minimal memory, processing time, etc., are lost.
13
0
8.0k
Sep ’21