Dive into the world of programming languages used for app development.

All subtopics

Post

Replies

Boosts

Views

Activity

Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, }
2
0
191
2w
clang multiarch doens't work with precompiled headers
So I found out clang can do multiarch compiles (-arch arm64 -arch x86_64). But Apple seems to have left precompiled header support out. So I built the pch separately for each arch. That all works. The next problem is that one needs to specify -include-pch foo.x64.pch and -include-pch foo.arm64.pch on the command line. This doesn't work on the compile line, since it tries to prepend arm64 AST to a x64 .o file, and vice versa. So there is -Xarch_arm64 and -Xarch_x86_64 . But that option is limited to one argument. But "-include-pch foo.x64.pch" is two arguments. More details of failed attempts here: https://github.com/llvm/llvm-project/issues/114626 And no splitting out the builds isn't the same, because then -valid_arch I don't think skips the other build. This are all libraries being built by Make, and then the universal app built using an Xcode project from the libraries.
2
0
187
2w
Memory crash at String._bridgeToObjectiveCImpl()
I'll describe my crash with an example, looking for some insights into the reason why this is happening. @objc public protocol LauncherContainer { var launcher: Launcher { get } } @objc public protocol Launcher: UIViewControllerTransitioningDelegate { func initiateLaunch(url: URL, launchingHotInstance: Bool) } @objc final class LauncherContainer: NSObject, LauncherContainer, TabsContentCellTapHandler { ... init( ... ) { ... super.init() } ... // // ContentCellTapHandler // public func tabContentCellItemDidTap( tabId: String ) { ... launcher.initiateNewTabNavigation( tabId: tabId // Crash happens here ) } public class Launcher: NSObject, Launcher, FooterPillTapHandler { public func initiateNewTabNavigation(tabId: String) { ... } } public protocol TabsContentCellTapHandler: NSObject { func tabContentCellItemDidTap( tabId: String, } Crash stack last 2 lines are- libswiftCore.dylib swift_unknownObjectRetain libswiftCore.dylib String._bridgeToObjectiveCImpl() String._bridgeToObjectiveCImpl() gets called when the caller and implementation is in Swift file I believe due to @objc class LauncherContainer there'd be bridging header generated. Does that mean tabId passed to tabContentCellItemDidTap is a String but the one passed to initiateNewTabNavigation is NSString? TabId is UUID().uuidString if that helps. Wondering if UUID().uuidString has something to do with this. Thanks a ton for helping. Please find attached screenshot of the stack trace.
1
0
192
2w
Token is not a valid binary operator in a preprocessor subexpression
I have a relatively unique project layered with file types (top to bottom) SwiftUI, Swift, Objective C, and C. The purpose of this layering is that I have a C language firmware application framework for development of firmware on custom electronic boards. Specifically, I use the standard C preprocessor in specific ways to make data driven structures, not code. There are header files shared between the firmware project and the Xcode iPhone app to set things like the BLE protocol and communication command/reply protocols, etc. The app is forced to adhere to that defined by the firmware, rather than rely a design to get it right. The Objective C code is mainly to utilize the Bluetooth stack provided by iOS. I specifically use this approach to allow C files to be compiled. Normally, everything has worked perfectly, but a serious and obtuse problem just surfaced a couple days ago. My important project was created long ago. More recently, I started a new project using most of the same technology, but its project is newer. Ironically, it continues to work perfectly, but ironically the older project stopped working. (Talking about the Xcode iOS side.) Essentially, the Objective C handling of the C preprocessor is not fully adhering to the standard C preprocessing in one project. It's very confusing because there is no code change. It seems Xcode was updated, but looks like the project was not updated, accordingly? I'm guessing there is some setting that forces Objective C to adhere to the standard C preprocessor rules. I did see a gnu compiler version that did not get updated compared to the newer project, but updating that in the Build Settings did not fix the problem. The error is in the title: Token is not a valid binary operator in a preprocessor subexpression. The offending macro appears in a header file, included in several implementation files. Compiling a single implementation files isolates the issue somewhat. An implementation with no Objective C objects compiles just fine. If there are Objective C objects then I get the errors. Both cases include the same header. It seems like the Objective C compiler, being invoked, uses a different C preprocessor parser, rather than the standard. I guess I should mention the bridging header file where these headers exist, as well. The offending header with the problem macro appears as an error in the bridging header if a full build is initiated. Is there an option somewhere, that forces the Objective C compiler to honor the standard C processor? Note, one project seems to. #define BLE_SERVICE_BLANK( enumTag, uuid, serviceType ) #define BLE_CHARACTERISTIC_BLANK( enumTag, uuid, properties, readPerm, writePerm, value) #define BLE_SERVICE_ENUM_COUNTER( enumTag, uuid, serviceType) +1 #define BLE_CHARACTERISTIC_ENUM_COUNTER( enumTag, uuid, properties, readPerm, writePerm, value) +1 #if 0 BLE_SERVICE_LIST(BLE_SERVICE_ENUM_COUNTER, BLE_CHARACTERISTIC_BLANK) > 0 #define USING_BLE_SERVICE ... #if 0 BLE_SERVICE_LIST(BLE_SERVICE_BLANK, BLE_CHARACTERISTIC_ENUM_COUNTER) > 0 #define USING_BLE_CHARACTERISTIC ... token is not a valid binary operator in a preprocessor subexpression refers to the comparison. BLE_SERVICE_LIST() does a +1 for each item in the list. There is no further expansion. One counts services. The other counts characteristics. The errors are associated with the comparisons.
6
0
225
2w
Directly operating on memory pointed by UnsafeMutableRawPointer
In my project, i have a Swift class with a class level property of type string. Like this : class TWSwiftString { var pString:String! init(_ pString: String) { self.pString = pString } } I am creating intance of this class and then creating a opaque pointer to this intance. Like this : let str = TWSwiftString("World") // Increasing RC by 1 strptr = Unmanaged.passRetained(str).toOpaque() Now using this opaque pointer i want to modify the value of pString by directly operating on memory. Like this: withUnsafeMutablePointer(to: &strptr.pString) { strPointer in strPointer.pointee = "World" } Although i am able to modify pString like this and print. Lets assume i have a approach to make sure memory remains valid when it is operated on and freeing of memory is also handled somehow . Will this approach work if i have 100s of intance of this string which are being operated in this manner ? What if the size of new value is greater than existing string value ? For this i am thinking of chunk of memory initially and then keep on increasing size of it as bigger string then this chunk comes. Does this approach seems feasible ? Any other problems i can encounter by using this approach ? Chatgpt gave this answer : To directly update the memory of a Swift class’s property, particularly to alter a String property, is generally discouraged due to Swift's memory safety model. However, if we want to access and modify a class property directly, the best practice is to use a property accessor, as manually altering memory could lead to undefined behavior or even crashes. Why Direct Memory Manipulation Is Risky When you attempt to manipulate memory directly, especially with Swift’s memory model, you might alter not only the value but also the memory layout of Swift’s String type, which could break things internally. The Swift compiler may store String differently based on the internal structure, so even if we manage to locate the correct memory address, directly modifying it is unreliable. do you have any opinion around chatgpt resoponse ?
1
0
113
2w
How to Remove OpaqueTypeErasure from SwiftUI
I am using swiftui lately in my iOS mobile app, The Mobile app already has a pipeline that detect any experimental features and throw an error I am using swift 5 and as you all know SwiftUI is using some of OpaqueTypeErasure utility types like "some" I heard that in swift 6 the OpaqueTypeErasure is not experimental anymore But upgrading the app swift version will be a very long process Also changing the pipeline will be a very long and tiring process So i want to know if there is a way to remove OpaqueTypeErasure from SwiftUI and what is the alternatives for bypassing the error that being thrown from the pipeline
3
0
181
2w
Is it possible to execute machine code on iOS with permission
When Xcode is connected to the mobile phone for debugging, the app that contains the logic of executing machine code runs normally, but if Xcode is disconnected and the app is run alone, it will crash. First use the xcode-run execution function to start the app The machine code logic executes normally Disconnect the phone from xcode Start the app 5.Crash Here is the test code:https://gitee.com/FanChiang_admin/demo.git
1
0
149
2w
Crash due to missing symbols from libc++ [macOS 11.7.10] [Big Sur]
We are seeing a crash on Big Sur 11.7.10 after switching the build system to use Xcode 15 Excerpt from crash Time Awake Since Boot: 1700 seconds System Integrity Protection: enabled Crashed Thread: 0 Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Reason: DYLD, [0x4] Symbol missing Application Specific Information: dyld: launch, loading dependent libraries Dyld Error Message: Symbol not found: __ZNSt3__17codecvtIDiDu11__mbstate_tE2idE Referenced from: /Applications/SecureworksTaegis.app/Contents/MacOS/com.secureworks.agent.daemon.app/Contents/MacOS/com.secureworks.agent.daemon Expected in: /usr/lib/libc++.1.dylib in /Applications/SecureworksTaegis.app/Contents/MacOS/com.secureworks.agent.daemon.app/Contents/MacOS/com.secureworks.agent.daemon Build system has the following specs : ProductName: macOS ProductVersion: 14.3.1 BuildVersion: 23D60 Xcode 15.2 Build version 15C500b CMAKE PROPS set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_OSX_DEPLOYMENT_TARGET 11.0)
5
0
317
2w
Trace/BPT trap in very simple C code compiled with clang
I wonder if this is correct behavior. I was surprised to get this result when compiling and running the following C code with Apple clang version 14.0.0 (clang-1400.0.29.102) target arm64-apple-darwin21.6.0 on a M1 Pro 12.7.6 with cc -O2 file.c: #include <stdio.h> #include <stdlib.h> unsigned long long factorial(int n) { unsigned long long fac = 1; while (n > 0) fac *= n; return fac; } int main() { return factorial(1); } Compiling with -O2 and running this code gives "Trace/BPT trap". Checking with LLDB: $ lldb ./a.out (lldb) target create "./a.out" Current executable set to '/Users/engelen/Projects/Euler/a.out' (arm64). (lldb) run Process 79580 launched: '/Users/engelen/Projects/Euler/a.out' (arm64) Process 79580 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BREAKPOINT (code=1, subcode=0x100003fb4) frame #0: 0x0000000100003fb4 a.out`main at 20.c:9:3 [opt] 6 unsigned long long fac = 1; 7 while (n > 0) 8 fac *= n; -> 9 return fac; 10 } 11 12 int main() The loop is non-terminating. But a breakpoint trap is triggered at the return statement. The code should just hang in the loop IMO, not trap, because it never updates variable n (a correct factorial function should decrement n). Never seen this before (not since I started wiring C code in the 80s.) If I change the update *= into += then there is no trap.
1
0
214
2w
Swift is new for me
i have macos 15 and xcode 16 swift 6 and want to make apps to run on macintosh. i know the syntax of this programming language, but i need informations like which libraries i have to import for func's which name i do not know, and parameters i have not found on websites or the tutorial on swift. i need procedures like open window at x,y,width,height draw rectangle at x,y,width,height,color draw text at x,y,width,height,color,size read keyboard-letter,up/dn,shift read mouse x,y,buttons
4
0
282
Oct ’24
@Observable in command line app
I have a problem with the following code, I am not being notified of changes to the progress property of my Job object, which is @Observable... This is a command-line Mac application (the same code works fine in a SwiftUI application). I must have missed something? do { let job = AsyncJob() withObservationTracking { let progress = job.progress } onChange: { print("Current progress: \(job.progress)") } let _ = try await job.run() print("Done...") } catch { print(error) } I Try this without any success: @main struct MyApp { static func main() async throws { // my code here } }
10
1
531
4w
Applescript seems to run in Rosetta on M2
When calling a perl script from an apple script (by dropping a file on it), I get the error: Can't load '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' for module Encode: dlopen(/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle, 0x0001): tried: '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/System/Volumes/Preboot/Cryptexes/OS/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (no such file), '/Library/Perl/5.34/darwin-thread-multi-2level/auto/Encode/Encode.bundle' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')) at /System/Library/Perl/5.34/XSLoader.pm line 96. at /Library/Perl/5.34/darwin-thread-multi-2level/Encode.pm line 12. When I call the script manually from terminal, it runs fine. Why is Applescript running as X86 on M2?
2
0
411
Sep ’24
SPM show-dependencies broken
I have a Package.swift // swift-tools-version: 5.9 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SharedUI", defaultLocalization: "en_US", platforms: [.iOS(.v16)], products: [ .library( name: "SharedUI", targets: [ "AppTheme", ] ), ], dependencies: [ .package(url: "https://github.com/apple/swift-markdown.git", "0.2.0"..<"0.3.0"), ], targets: [ .target( name: "AppTheme", dependencies: [ .product(name: "Markdown", package: "swift-markdown"), ], path: "AppTheme" ), ] ) Run swift package show-dependencies shows error yuantong-macbookpro2:Downloads yuantong$ swift package show-dependencies Fetching https://github.com/apple/swift-markdown.git from cache Fetched https://github.com/apple/swift-markdown.git (0.67s) error: Couldn’t get the list of tags: fatal: cannot use bare repository '/Users/yuantong/Downloads/.build/repositories/swift-markdown-b692ce3c' (safe.bareRepository is 'explicit') which I think used to work before Xcode 15.
8
4
1.4k
Feb ’24
Testing the content of a `Task` in a non-async method
Hi, Considering this method I'd like to test: public func play(_ soundFileName: String, shouldLoop: Bool) { Task { await dataSource.play(soundFileName, shouldLoop: shouldLoop) } } Previously, with XCTest we could use an expectation and wait for it to be fulfilled: func test() sut.play("", shouldLoop: false) wait(for: [mockedAudioPlayerDataSource.invokedPlayExpectation]) XCTAssertEqual(mockedAudioPlayerDataSource.invokedPlayCount, 1) With Swift Testing, I am unsure what a unit test looks like.
4
0
290
4w
Sending 'self' risks causing data races
Hi! I'm trying to implement Swift 6 in my code but can't fix one problem. Here is my code example which could be run in playground: import UIKit import WatchConnectivity public final class MulticastDelegate<T>: Sendable { nonisolated(unsafe) private var delegates = [WeakWrapper]() public init() { } public var isEmpty: Bool { return delegates.isEmpty } public func addDelegate(_ delegate: T) { let wrapper = WeakWrapper(value: delegate as AnyObject) delegates.append(wrapper) } public func removeDelegate(_ delegate: T) { delegates = delegates.filter { $0.value !== delegate as AnyObject } } public func invokeDelegates(_ invocation: (T) -> Void) { for (index, delegate) in delegates.enumerated().reversed() { if let delegate = delegate.value as? T { invocation(delegate) } else { delegates.remove(at: index) } } } public func invokeDelegatesCheckingResponse(_ invocation: (T) -> Bool) -> Bool { var isHandled = false for delegate in delegates { if let delegate = delegate.value as? T { if invocation(delegate) { isHandled = true break } } } return isHandled } private final class WeakWrapper: Sendable { nonisolated(unsafe) weak var value: AnyObject? init(value: AnyObject) { self.value = value } } } @globalActor public actor WatchActor { public static var shared = WatchActor() } @MainActor @objc public protocol WatchCommunicatorDelegate: NSObjectProtocol { @objc optional func watchCommunicatorDidRequestDataUpdate(_ controller: WatchCommunicator) } @WatchActor @objc public final class WatchCommunicator: NSObject { private let multicastDelegate = MulticastDelegate<WatchCommunicatorDelegate>() } extension WatchCommunicator: @preconcurrency WCSessionDelegate { public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) { multicastDelegate.invokeDelegates { delegate in Task { @MainActor in delegate.watchCommunicatorDidRequestDataUpdate?(self) } } } public func sessionDidBecomeInactive(_ session: WCSession) { } public func sessionDidDeactivate(_ session: WCSession) { } } I want to work with WatchCommunicator in global actor and WatchCommunicatorDelegate should be call in main actor and should have reference to WatchCommunicator. Help please
2
0
462
4w
Xcode "Build documentation" not working with Swift Macro package in project
I have a workspace with my project and a Swift Macro. When I use the "Build Documentation" command the build fails with this error: fatal error: module map file '/Users/me/Library/Developer/Xcode/DerivedData/Project-fmdkuqlofexbqdhhitpgjnoqzyrz/Build/Intermediates.noindex/GeneratedModuleMaps-iphoneos/Macros.modulemap' not found Is there a way around this?
2
1
751
Feb ’24
MPMediaItemPropertyArtwork crashes on Swift 6
Hey all! in my personal quest to make future proof apps moving to Swift 6, one of my app has a problem when setting an artwork image in MPNowPlayingInfoCenter Here's what I'm using to set the metadata func setMetadata(title: String? = nil, artist: String? = nil, artwork: String? = nil) async throws { let defaultArtwork = UIImage(named: "logo")! var nowPlayingInfo = [ MPMediaItemPropertyTitle: title ?? "***", MPMediaItemPropertyArtist: artist ?? "***", MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } ] as [String: Any] if let artwork = artwork { guard let url = URL(string: artwork) else { return } let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { return } guard let image = UIImage(data: data) else { return } nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } } MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } the app crashes when hitting MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } or nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } commenting out these two make the app work again. Again, no clue on why. Thanks in advance
6
0
492
Sep ’24
Is there any way to write a screensaver for macOS using Python Pygame?
I want to be able to write a cross-platform screensaver that works on both Windows and macOS using the Pygame 2D graphics library in Python. On Windows, this is super easy - you just write your program with three possible command line arguments: /p for preview mode, /c for the configuration dialog mode, and /s for the actual full-screen screensaver mode. Then you just use pyinstaller to build an .exe file and rename the extension to .scr, and you're good to go. However, it seems that making a screensaver on macOS is a pretty convoluted process, and there was stuff about specific Objective-C functions that you had to write, and I didn't really understand the documentation. Could you please tell me if there is any way to simply get my Python Pygame program to build as a proper .saver file? Thanks!
1
0
208
Oct ’24