I can compile this
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (strong) NSWindow *window;
@property (strong) NSSlider *slider;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    // Window size
    NSRect frame = NSMakeRect(0, 0, 400, 300);
    NSUInteger style = NSWindowStyleMaskTitled |
                       NSWindowStyleMaskClosable |
                       NSWindowStyleMaskResizable;
    self.window = [[NSWindow alloc] initWithContentRect:frame
                                              styleMask:style
                                                backing:NSBackingStoreBuffered
                                                  defer:NO];
    [self.window setTitle:@"Centered Slider Example"];
    [self.window makeKeyAndOrderFront:nil];
    // Slider size
    CGFloat sliderWidth = 200;
    CGFloat sliderHeight = 32;
    CGFloat windowWidth = self.window.frame.size.width;
    CGFloat windowHeight = self.window.frame.size.height;
    CGFloat sliderX = (windowWidth - sliderWidth) / 2;
    CGFloat sliderY = (windowHeight - sliderHeight) / 2;
    self.slider = [[NSSlider alloc] initWithFrame:NSMakeRect(sliderX, sliderY, sliderWidth, sliderHeight)];
    [self.slider setMinValue:0];
    [self.slider setMaxValue:100];
    [self.slider setDoubleValue:50];
    [self.window.contentView addSubview:self.slider];
}
@end
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSApplication *app = [NSApplication sharedApplication];
        AppDelegate *delegate = [[AppDelegate alloc] init];
        [app setDelegate:delegate];
        [app run];
    }
    return 0;
}
with
(base) johnzhou@Johns-MacBook-Pro liquidglasstest % clang -framework Foundation -framework AppKit testobjc.m
and get this neat liquid glass effect:
https://github.com/user-attachments/assets/4199493b-6011-4ad0-9c9f-25db8585e547
However if I use pyobjc to make an equivalent
import sys
from Cocoa import (
    NSApplication, NSApp, NSWindow, NSSlider, NSMakeRect,
    NSWindowStyleMaskTitled, NSWindowStyleMaskClosable,
    NSWindowStyleMaskResizable, NSBackingStoreBuffered,
    NSObject
)
class AppDelegate(NSObject):
    def applicationDidFinishLaunching_(self, notification):
        # Create the main window
        window_size = NSMakeRect(0, 0, 400, 300)
        style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable
        self.window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            window_size, style, NSBackingStoreBuffered, False
        )
        self.window.setTitle_("Centered Slider Example")
        self.window.makeKeyAndOrderFront_(None)
        # Slider size and positioning
        slider_width = 200
        slider_height = 32
        window_width = self.window.frame().size.width
        window_height = self.window.frame().size.height
        slider_x = (window_width - slider_width) / 2
        slider_y = (window_height - slider_height) / 2
        self.slider = NSSlider.alloc().initWithFrame_(NSMakeRect(slider_x, slider_y, slider_width, slider_height))
        self.slider.setMinValue_(0)
        self.slider.setMaxValue_(100)
        self.slider.setDoubleValue_(50)
        self.window.contentView().addSubview_(self.slider)
if __name__ == "__main__":
    app = NSApplication.sharedApplication()
    delegate = AppDelegate.alloc().init()
    app.setDelegate_(delegate)
    app.run()
I get a result shown at
https://github.com/user-attachments/assets/7da022bc-122b-491d-9e08-030dcb9337c3
which does not have the new liquid glass effect.
Why is this?  Is this perhaps related to the requirement that you must compile on latest Xcode as indicated in the docs?  Why, is the compiler doing some magic?
                    
                  
                Objective-C Runtime
RSS for tagThe Objective-C runtime is a runtime library that supports the dynamic properties of the Objective-C language.
Posts under Objective-C Runtime tag
            
              
                17 Posts
              
            
            
              
                
              
            
          
          
  
    
    Selecting any option will automatically load the page
  
  
  
  
    
  
  
              Post
Replies
Boosts
Views
Activity
                    
                      I have been banging my head against this problem for a bit now.
I am trying to build a bidirectional, infinitely scrolling list that implements these core requirements:
Loads data up/down on the fly as the user scrolls
Preserves scroll velocity as the list is updated
Restores the scroll to the exact visual location after data has changed
Ensures no flicker when restoring scroll position - the user cannot know the list has updated and should continue scrolling as normal
Because LazyVStack does not play well with animations, I am opting to go with VStack and am implementing my own sliding window for data. This means that data can be removed as well as added, and a simple application of a height delta is not enough when restoring position.
So far I have tried many things:
Relying on ScrollPosition - simply does not work by itself as described (swift UI trying to keep the position stable with ID's)
Relying on ScrollPosition.scrollTo - only kind of works with ID, no way to restore position with pixel perfect accuracy
Intercepting the UIKit scrollView instance, using it to record and access the top row's position, mutating data and then queuing a scroll restoration using CATransaction.setCompletionBlock - this is the closest I've come, and it satisfies the top 3 requirements but sometimes I get a flicker on slightly heavier lists
What I would really like, is a way of using ScrollView and granularly hooking into the lifecycle of the view after layout, and just before draw. At this point I would update the relevant scroll positions, and allow draw to continue. Is this possible? My knowledge is very limited at this point, but I believe I may be able to achieve something of the sort by swizzling layerWillDraw? Does this make sense, and is it prudent?
In general, I'm very interesting in hearing what people have to say about the above, as well as this problem in general.
                    
                  
                
                    
                      After swapping the -objectAtIndex: method using method_exchangeImplementations, it will cause continuous memory growth.
Connect the iPhone and run the provided project.
Continuously tap the iPhone screen.
Observe Memory; it will keep growing.
Sample code
                    
                  
                
              
                
              
              
                
                Topic:
                  
	
		Programming Languages
  	
                
                
                SubTopic:
                  
                    
	
		General
		
  	
                  
                
              
              
                Tags:
              
              
  
  
    
      
      
      
        
          
            Objective-C Runtime
          
        
        
      
      
    
      
      
      
        
          
            Xcode Sanitizers and Runtime Issues
          
        
        
      
      
    
      
      
      
        
          
            Foundation
          
        
        
      
      
    
  
  
              
                
                
              
            
          
                    
                      I’m an amateur developer working on a free utility for composers/producers, for which the macOS release needs to create and name RTP-MIDI sessions in Audio MIDI Setup from the command line (so I can ship a small C helper instead of telling users to click through the UI). Here’s what I’ve tried so far, without luck:
• Plist hacks: Injecting  entries into ~/Library/Audio/MIDI Configurations/*.mcfg works when AMS is closed, but AMS immediately locks and reverts my changes when it’s open.
• CoreMIDI C API: I can create virtual ports with MIDISourceCreate, but attempting MIDIObjectGetDataProperty on the apple.midirtp.session plugin always returns err –10836.
• Obj-C & Swift: Loading MIDINetworkSession and calling defaultSession, init, setNetworkName: and setting enabled = YES doesn’t produce a new session object in the Network panel.
• dlopen/dlsym: I extracted the real CoreMIDI binary out of the dyld shared cache and tried binding _MIDINetworkSessionCreate, _SetName, _SetEnabled, etc., but all the symbols come back null or my tool segfaults.
• Plugin registration: I’ve pulled the factory UUID (70C9C5EA-7C65-11D8-B317-000393A34B5A) from /System/Library/Extensions/AppleMIDIRTPDriver.plugin/Contents/Info.plist and called CFPlugInRegisterFactories, but it still never exposes the session-creation calls.
At this point I’m convinced I’m either loading the wrong binary or missing one critical step in registering the RTP-MIDI plugin’s private API. Can anyone point me to:
The exact path of the dylib or bundle that actually exports the MIDINetworkSessionCreate/MIDINetworkSessionSetName/MIDINetworkSessionSetEnabled symbols?
A minimal working snippet (C or Obj-C) that reliably creates and names a Network-MIDI session?
Any pointers, sample code, or even ideas about where Apple hides this functionality on macOS 15 would be hugely appreciated. Thanks!
                    
                  
                
                    
                      Under multiple display screens (left and right screens), when a commonly used app application clicks "Window" -> "Move to..." When it comes to this, the app cannot be completely moved to the other window but instead moves to the middle of the two Windows for display. Is this a bug of the system?
                    
                  
                
                    
                      Hi All
my app randomly crash on very rare case. when bring app into foreground
I checked the code:
{
    NSError *error = nil;
    
    if (![sender authenticateWithPassword:MyManager.sharedManager.service.authToken.accessToken error:&error]) {
...
...
...
    }
}
accessToken is NSString type,  was that because accessToken is deallocated?
Manager and service could not be nil at all.
Last Exception Backtrace:
0   CoreFoundation                	       0x18b04d2ec __exceptionPreprocess + 164
1   libobjc.A.dylib               	       0x1884d1a7c objc_exception_throw + 88
2   CoreFoundation                	       0x18b0b767c +[NSObject(NSObject) _copyDescription] + 0
3   CoreFoundation                	       0x18af64b84 ___forwarding___ + 1492
4   CoreFoundation                	       0x18af644f0 _CF_forwarding_prep_0 + 96
5   PTComms                       	       0x102adafac __45-[XMPPStream authenticateWithPassword:error:]_block_invoke + 1884
6   libdispatch.dylib             	       0x192ecb584 _dispatch_client_callout + 16
7   libdispatch.dylib             	       0x192ec1b4c _dispatch_sync_invoke_and_complete_recurse + 64
8   libdispatch.dylib             	       0x192ec15dc _dispatch_sync_f_slow + 176
9   PTComms                       	       0x102ada760 -[XMPPStream authenticateWithPassword:error:] + 516
10  PTComms                       	       0x102a7b6f0 -[CommsService xmppStreamDidConnect:] + 160
11  CoreFoundation                	       0x18af64434 __invoking___ + 148
12  CoreFoundation                	       0x18af65044 -[NSInvocation invoke] + 424
13  CoreFoundation                	       0x18afbb6b8 -[NSInvocation invokeWithTarget:] + 64
14  PTComms                       	       0x102b391c8 __42-[GCDMulticastDelegate forwardInvocation:]_block_invoke + 68
15  libdispatch.dylib             	       0x192eb1aac _dispatch_call_block_and_release + 32
16  libdispatch.dylib             	       0x192ecb584 _dispatch_client_callout + 16
17  libdispatch.dylib             	       0x192ee8574 _dispatch_main_queue_drain.cold.5 + 812
18  libdispatch.dylib             	       0x192ec0d30 _dispatch_main_queue_drain + 180
19  libdispatch.dylib             	       0x192ec0c6c _dispatch_main_queue_callback_4CF + 44
20  CoreFoundation                	       0x18afa62b4 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16
21  CoreFoundation                	       0x18afa40b0 __CFRunLoopRun + 1980
22  CoreFoundation                	       0x18afc8700 CFRunLoopRunSpecific + 572
23  GraphicsServices              	       0x1d7b09190 GSEventRunModal + 168
24  UIKitCore                     	       0x18dbe6240 -[UIApplication _run] + 816
25  UIKitCore                     	       0x18dbe4470 UIApplicationMain + 336
26  VoceraEdgeComms               	       0x102542318 0x10253c000 + 25368
27  dyld                          	       0x1b19cbad8 start + 5964
Thread 0 name:   Dispatch queue: xmpp
Thread 0 Crashed:
0   libsystem_kernel.dylib        	       0x1dbb3a1dc __pthread_kill + 8
1   libsystem_pthread.dylib       	       0x2154b8b40 pthread_kill + 268
2   libsystem_c.dylib             	       0x192f6d360 __abort + 132
3   libsystem_c.dylib             	       0x192f6d2dc abort + 136
4   libc++abi.dylib               	       0x2153e25a0 abort_message + 132
5   libc++abi.dylib               	       0x2153d0f10 demangling_terminate_handler() + 344
6   libobjc.A.dylib               	       0x1884d3bb8 _objc_terminate() + 156
7   PTCore                        	       0x1061f0d98 FIRCLSTerminateHandler() (.cold.3) + 56
8   PTCore                        	       0x1060ef7e8 FIRCLSTerminateHandler() + 276
9   libc++abi.dylib               	       0x2153e18b4 std::__terminate(void (*)()) + 16
10  libc++abi.dylib               	       0x2153e4e1c __cxxabiv1::failed_throw(__cxxabiv1::__cxa_exception*) + 88
11  libc++abi.dylib               	       0x2153e4dc4 __cxa_throw + 92
12  libobjc.A.dylib               	       0x1884d1be4 objc_exception_throw + 448
13  CoreFoundation                	       0x18b0b767c -[NSObject(NSObject) doesNotRecognizeSelector:] + 364
14  CoreFoundation                	       0x18af64b84 ___forwarding___ + 1492
15  CoreFoundation                	       0x18af644f0 _CF_forwarding_prep_0 + 96
16  PTComms                       	       0x102adafac __45-[XMPPStream authenticateWithPassword:error:]_block_invoke +
Thanks,
CrashReporter.txt
                    
                  
                
                    
                      Is there a way to prevent or handle our application's crash if a third-party library makes a bad memory access? Basically, I want to know if using a buggy library (that causes bad memory access) will automatically make our application inherit those crashes, leading to our app crashing as well. If there is a way to prevent the crash, what methods can be used to do so?
Thread 13: EXC_BAD_ACCESS (code=1, address=0x3a7d300)
                    
                  
                
                    
                      When I run app, it works on iOS16+ device. But when I run on iOS15 device just working on debug mode, if I run release or profile modeI got runtime error:
Log:
(lldb) dyld[4928]: Symbol not found: (_objc_claimAutoreleasedReturnValue)
Referenced from: '/private/var/containers/Bundle/Application/C724D7C6-82FA-4AF3-AE83-EC035B4429A5/Runner.app/Frameworks/geolocator_apple.framework/geolocator_apple'
Expected in: '/usr/lib/libobjc.A.dylib'
thread #1, stop reason = signal SIGABRT
frame #0: 0x0000000106cbb2cc dyld`__abort_with_payload + 8
dyld`__abort_with_payload:
-&gt;  0x106cbb2cc &lt;+8&gt;:  b.lo   0x106cbb2e8               ; &lt;+36&gt;
0x106cbb2d0 &lt;+12&gt;: stp    x29, x30, [sp, #-0x10]!
0x106cbb2d4 &lt;+16&gt;: mov    x29, sp
0x106cbb2d8 &lt;+20&gt;: bl     0x106c8164c               ; cerror_nocancel
Target 0: (Runner) stopped.
Flutter doctor :
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.29.2, on macOS 15.2 24C101 darwin-arm64, locale en-VN)
[✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 16.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2024.2)
[✓] VS Code (version 1.97.2)
                    
                  
                
                    
                      My company wants to be insure that if my Objective-C to Swift conversions fail in anyway, that the app can revert to using the older Objective-C code. By using a remotely controllable flag, the app can switch which code runs as, both are compiled into the app.
Essentially, I create a protocol that describes the original class, then both classes (with a "s" or "o" appended to them) conform to the protocol.
Protocol: Object
Objective-C class: oObject
Swift class: sObject
That said, I hit one issue that I just can't seem reason out. I create a Objective-C function that returns the appropriate class:
Class<Object> classObject(void) {
    if (myFlag) {
        return [sObject class];
    } else {
       return [oObject class];
    }
}
Swift deals with this really well - I can create an initialized object using:
let object = classObject().init()
but I cannot find a way to do this in Objective-C:
Object *object = [[classSalesForceData() alloc] init]; 
fails with "No known class method for selector 'alloc'"
Is there a way to do this?
David
PS: my workaround is to return an allocated object:
Object *createObject(void) {
    if (myFlag) {
        return [sObject alloc];
    } else {
       return [oObject alloc];
    }
}
                    
                  
                
                    
                      After the app is put in background for sometime and brought in to foreground and the app crashes each time with a different thread stack entries but all of them states same exception reason.
                    
                  
                
                    
                      Hello!
I have a swift program that tracks the location of a ball (through the back camera). It seems to be working fine, but the only issue is the run time, particularly my concatenate, normalize, and argmax functions, which are meant to be a 1 to 1 copy of the PyTorch argmax function and the following python lines:
imgs = np.concatenate((img, img_prev, img_preprev), axis=2)
imgs = imgs.astype(np.float32)/255.0
imgs = np.rollaxis(imgs, 2, 0)
inp = np.expand_dims(imgs, axis=0) # used to pass into model
However, I need my program to run in real time and in an ideal world, I want it to run way under real time. Below is a run down of the run times that result from my code:
Starting model inference
Setup took: 0.0 seconds
Resize took: 0.03741896152496338 seconds
Concatenation took: 0.3359949588775635 seconds
Normalization took: 0.9906361103057861 seconds
Model prediction took: 0.3425499200820923 seconds
Argmax took: 28.17007803916931 seconds
Postprocess took: 0.054128050804138184 seconds
Model inference took 29.934185028076172 seconds
Here are the concatenateBuffers, normalizeBuffers, and argmax functions that I use:
func concatenateBuffers(_ buffers: [CVPixelBuffer?]) -> CVPixelBuffer? {
    guard buffers.count == 3, let first = buffers[0] else { return nil }
    let width = CVPixelBufferGetWidth(first)
    let height = CVPixelBufferGetHeight(first)
    let targetChannels = 9
    
    var concatenated: CVPixelBuffer?
    let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue] as CFDictionary
    CVPixelBufferCreate(kCFAllocatorDefault, width, height, kCVPixelFormatType_32BGRA, attrs, &concatenated)
    guard let output = concatenated else { return nil }
    
    CVPixelBufferLockBaseAddress(output, [])
    defer { CVPixelBufferUnlockBaseAddress(output, []) }
    
    guard let outputData = CVPixelBufferGetBaseAddress(output) else { return nil }
    let outputPtr = UnsafeMutablePointer<UInt8>(OpaquePointer(outputData))
    
    // Lock all input buffers at once
    buffers.forEach { buffer in
        guard let buffer = buffer else { return }
        CVPixelBufferLockBaseAddress(buffer, .readOnly)
    }
    defer {
        buffers.forEach { CVPixelBufferUnlockBaseAddress($0!, .readOnly) }
    }
    
    // Process each input buffer
    for (frameIdx, buffer) in buffers.enumerated() {
        guard let buffer = buffer,
              let inputData = CVPixelBufferGetBaseAddress(buffer) else { continue }
        
        let inputPtr = UnsafePointer<UInt8>(OpaquePointer(inputData))
        let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer)
        let totalPixels = width * height
        
        // Process all pixels in one go for this frame
        for i in 0..<totalPixels {
            let y = i / width
            let x = i % width
            
            let inputOffset = y * bytesPerRow + x * 4
            let outputOffset = i * targetChannels + frameIdx * 3
            
            // BGR order to match numpy
            outputPtr[outputOffset] = inputPtr[inputOffset + 2]     // B
            outputPtr[outputOffset + 1] = inputPtr[inputOffset + 1] // G
            outputPtr[outputOffset + 2] = inputPtr[inputOffset]     // R
        }
    }
    
    return output
}
func normalizeBuffer(_ buffer: CVPixelBuffer?) -> MLMultiArray? {
    guard let input = buffer else { return nil }
    
    let width = CVPixelBufferGetWidth(input)
    let height = CVPixelBufferGetHeight(input)
    let channels = 9
    
    CVPixelBufferLockBaseAddress(input, .readOnly)
    defer { CVPixelBufferUnlockBaseAddress(input, .readOnly) }
    
    guard let inputData = CVPixelBufferGetBaseAddress(input) else { return nil }
    
    let shape = [1, NSNumber(value: channels), NSNumber(value: height), NSNumber(value: width)]
    guard let output = try? MLMultiArray(shape: shape, dataType: .float32) else { return nil }
    
    let inputPtr = inputData.assumingMemoryBound(to: UInt8.self)
    let bytesPerRow = CVPixelBufferGetBytesPerRow(input)
    
    let ptr = UnsafeMutablePointer<Float>(OpaquePointer(output.dataPointer))
    let totalSize = width * height
    
    for c in 0..<channels {
        for idx in 0..<totalSize {
            let h = idx / width
            let w = idx % width
            let inputIdx = h * bytesPerRow + w * channels + c
            ptr[c * totalSize + idx] = Float(inputPtr[inputIdx]) / 255.0
        }
    }
    
    return output
}
func argmax(_ array: MLMultiArray) -> MLMultiArray? {
    let shape = array.shape.map { $0.intValue }
    guard shape.count == 3,
          shape[0] == 1,
          shape[1] == 256,
          shape[2] == 230400 else {
        return nil
    }
    
    guard let output = try? MLMultiArray(shape: [1, NSNumber(value: 230400)], dataType: .int32) else { return nil }
    
    let ptr = UnsafePointer<Float>(OpaquePointer(array.dataPointer))
    let outputPtr = UnsafeMutablePointer<Int32>(OpaquePointer(output.dataPointer))
    
    let channelSize = 230400
    
    for pos in 0..<230400 {
        var maxValue = -Float.infinity
        var maxIndex: Int32 = 0
        
        for channel in 0..<256 {
            let value = ptr[channel * channelSize + pos]
            if value > maxValue {
                maxValue = value
                maxIndex = Int32(channel)
            }
        }
        
        outputPtr[pos] = maxIndex
    }
    
    return output
}
Are there any glaring areas of inefficiencies that can be reduced to allow for under real time processing whilst following the same logic as found in the python code exactly? Would using Obj-C speed things up for some reason? Are there any tools I can use so I don't have to write these functions myself?
Additionally, in the classes init, function, I tried to check the compute units being used since I feel 0.34 seconds for a singular model prediction is also far too long, but no print statements are showing for some reason:
init() {
        guard let loadedModel = try? BallTrackerModel() else {
            fatalError("Could not load model")
        }
        let config = MLModelConfiguration()
        config.computeUnits = .all
        guard let configuredModel = try? BallTrackerModel(configuration: config) else {
            fatalError("Could not configure model")
        }
        self.model = configuredModel
        print("model loaded with compute units \(config.computeUnits.rawValue)")
    }
Thanks!
                    
                  
                
                    
                      Hello everyone,
There is one thing about Objective-C's memory management that confuses me, which is a returned object's lifetime from methods with names doesn't start with "alloc", "new", "copy", or "mutableCopy".
Take this as an example, when using NSBitmapImageRep's representationUsingType:properties: method, it returns an NSData object (reference: https://developer.apple.com/documentation/appkit/nsbitmapimagerep/representation(using:properties:)?language=objc).
While testing this out, the NSData seemed to be an owned object (it doesn't get released until the end of the program).
From what I understand, this may be an auto-released object which is released at the end of an autorelease pool block.
Could someone explain this in more detail? What if I want to release that NSData object before the end of the autorelease pool block? How can I know which object is autoreleased, borrowed, or owned?
                    
                  
                
                    
                      I have a class object created dynamically using Runtime, and I want to release some manually allocated memory resources when this object is deallocated. To achieve this, I added a custom implementation of the dealloc method using the following code:
SEL aSel = NSSelectorFromString(@"dealloc");
class_addMethod(kvoClass, aSel, (IMP)custom_dealloc, method_getTypeEncoding(class_getInstanceMethod(kvoClass, aSel)));
However, I encountered some issues. If I don't call the superclass's dealloc method in the cus_dealloc function, the superclass's dealloc implementation will not be executed. On the other hand, if I explicitly call the superclass's dealloc method, the program crashes.
Here is the implementation of the cus_dealloc function:
void custom_dealloc(id self, SEL _cmd) {
    // Release other memory

    
    Class superClass = class_getSuperclass(object_getClass(self));
    void (*originIMP)(struct objc_super *, SEL, ...) = (void *)objc_msgSendSuper;
    struct objc_super *objcSuper = &(struct objc_super){self, superClass};
    originIMP(objcSuper, _cmd);
}
demo
                    
                  
                
                    
                      My app's top crash is a mysterious one and I can't seem to figure it out. It always crashes on
_objc_fatalv(unsigned long long, unsigned long long, char const*, char*)
But the stack traces include a few different possible culprits like
NavigationBridge_PhoneTV.pushTarget(isDetail:)
UIKitNavigationBridge.update(environment:) 
ViewRendererHost.updateGraph()
UIScrollView(SwiftUI) _swiftui_adjustsContentInsetWhenScrollDisabled
Crash reports here:
2024-12-02_21-37-21.7864_-0600-1e78918e5586309b96a1c2986ff722778dec8a77.crash
2024-12-02_19-18-29.1251_-0500-a2fc5513683cd647b4adbbe03cc59e4a09237b5f.crash
2024-12-01_11-59-09.8888_-0500-9eb224ab3d37e76d0b966ea83473f584ac3bbe18.crash
2024-11-28_17-17-38.4808_+0100-46208989f016fbefd16c30873a88c2ef61dd91a1.crash
Hopefully someone here can shed some light. For context we use a lot of UIHostingController's to bridge our SwiftUI views.
                    
                  
                
                    
                      Hey there! My app's top crash is a mysterious one and I can't seem to figure it out. Hopefully someone here can shed some light. For context we use a lot of UIHostingController's to bridge our SwiftUI views.
Crashed: com.apple.main-thread
0  libsystem_kernel.dylib         0x13ec4 __abort_with_payload + 8
1  libsystem_kernel.dylib         0x33bec abort_with_payload_wrapper_internal + 104
2  libsystem_kernel.dylib         0x33b84 abort_with_payload_wrapper_internal + 30
3  libobjc.A.dylib                0xbea0 _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 116
4  libobjc.A.dylib                0xbe2c _objc_fatalv(unsigned long long, unsigned long long, char const*, char*) + 30
5  libobjc.A.dylib                0xb040 weak_register_no_lock + 396
6  libobjc.A.dylib                0xa9bc objc_initWeak + 440
7  libswiftCore.dylib             0x43abe8 swift_unknownObjectWeakInit + 92
8  SwiftUI                        0xf40cc NavigationBridge_PhoneTV.pushTarget(isDetail:) + 376
9  SwiftUI                        0xf9490 UIKitNavigationBridge.update(environment:) + 1060
10 SwiftUI                        0x5b51c UIHostingController._update(environment:) + 156
11 SwiftUI                        0x96a30 _UIHostingView.updateEnvironment() + 3484
12 SwiftUICore                    0xa0d0a0 closure #1 in ViewRendererHost.updateGraph() + 364
13 SwiftUICore                    0xa0ca08 ViewRendererHost.updateGraph() + 180
14 SwiftUICore                    0xa0d7d4 closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 368
15 SwiftUICore                    0xa0b0d4 ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 556
16 SwiftUI                        0x8f1634 UIHostingViewBase.renderForPreferences(updateDisplayList:) + 168
17 SwiftUI                        0x8f495c closure #1 in UIHostingViewBase.requestImmediateUpdate() + 72
18 SwiftUI                        0xcc700 thunk for @escaping @callee_guaranteed () -> () + 36
19 libdispatch.dylib              0x2370 _dispatch_call_block_and_release + 32
20 libdispatch.dylib              0x40d0 _dispatch_client_callout + 20
21 libdispatch.dylib              0x129e0 _dispatch_main_queue_drain + 980
22 libdispatch.dylib              0x125fc _dispatch_main_queue_callback_4CF + 44
23 CoreFoundation                 0x56204 CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 16
24 CoreFoundation                 0x53440 __CFRunLoopRun + 1996
25 CoreFoundation                 0x52830 CFRunLoopRunSpecific + 588
26 GraphicsServices               0x11c4 GSEventRunModal + 164
27 UIKitCore                      0x3d2eb0 -[UIApplication _run] + 816
28 UIKitCore                      0x4815b4 UIApplicationMain + 340
29 (MyApp)                            0x1a7e0 main + 8 (main.swift:8)
30 ???                            0x1bf97eec8 (Missing)
                    
                  
                
                    
                      This is similar to this post https://developer.apple.com/forums/thread/700770 on using objc_copyClassList to obtain the available classes. When iterating the list, I try casting the result to an instance of a protocol and that works fine:
    protocol DynamicCounter {
        init(controlledByPlayer: Bool, game: Game)
    }
    class BaseCounter: NSObject, DynamicCounter {
    }
    static func withAllClasses<R>(
      _ body: (UnsafeBufferPointer<AnyClass>) throws -> R
    ) rethrows -> R {
      var count: UInt32 = 0
      let classListPtr = objc_copyClassList(&count)
      defer {
        free(UnsafeMutableRawPointer(classListPtr))
      }
      let classListBuffer = UnsafeBufferPointer(
        start: classListPtr, count: Int(count)
      )
      return try body(classListBuffer)
    }
    
    static func initialize() {
        let monoClasses = withAllClasses { $0.compactMap { $0 as? DynamicCounter.Type } }
        for cl in monoClasses {
            cl.initialize()
        }
    }
The above code works fine if I use DynamicCounter.Type on the cast but crashes if try casting to BaseCounter.Type instead.
Is there a way to avoid the weird and non Swift classes?
                    
                  
                
                    
                      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,
}