Objective-C

RSS for tag

Objective-C is a programming language for writing iOS, iPad OS, and macOS apps.

Posts under Objective-C tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Issues to access Swift code located in ObjC static library
I have an iOS app with the following configuration: My own ObjC static library project - MyStaticLib My own ObjC app target project - MyApp I have both projects in the same Xcode workspace so that MyStaticLib is linked successfully to MyApp Both projects have a mix of ObjC and Swift code successfully working. Currently: MyStaticLib: ObjC code can access Swift code and vice versa MyApp: ObjC code can access Swift code and vice versa ObjC code from MyApp can access ObjC code from MyStaticLib (This is achieved by adding Copy Files in Build Phases at MyStaticLib project settings with the ObjC header files) Objective: Swift code located in MyApp to access Swift code located in MyStaticLib Issues: If I'm trying to call a public Swift function located in MyStaticLib from MyApp, I get Cannot find 'YYY' in scope. If I'm adding import MyStaticLib, I get dozens of Duplicate interface definition for class 'ZZZ' Any idea how to resolve this?
0
0
296
Nov ’23
AXUIElementCopyAttributeValues crashing on macOS Sonoma
Stack trace OS Version: macOS 14.1 (23B74) Report Version: 104 Crashed Thread: 1622089 Application Specific Information: Fatal Error: EXC_BAD_ACCESS / KERN_PROTECTION_FAILURE / 0x16c91ffc0 Thread 1622089 Crashed: 0 libsystem_malloc.dylib 0x189cfcbc4 tiny_malloc_from_free_list 1 libsystem_malloc.dylib 0x189cfb2c4 szone_malloc_should_clear 2 Electron Framework 0x10e39f904 allocator_shim::MallocZoneFunctionsToReplaceDefault::lambda::__invoke (allocator_shim.cc:232) 3 CoreFoundation 0x189f5273c __CFStrAllocateMutableContents 4 CoreFoundation 0x189f52028 __CFStringChangeSizeMultiple 5 CoreFoundation 0x189f6d62c __CFStringAppendBytes 6 CoreFoundation 0x189f6c454 __CFStringAppendFormatCore 7 CoreFoundation 0x18a0a0ad0 _CFStringCreateWithFormatAndArgumentsReturningMetadata 8 CoreFoundation 0x189fb3e48 CFStringCreateWithFormatAndArguments 9 CoreFoundation 0x189f69e1c CFStringCreateWithFormat 10 HIServices 0x1903291a8 setWasOnceAuthorizeForAccessibility 11 HIServices 0x1903235a0 AXUIElementCopyAttributeValues
2
1
487
Nov ’23
How to disable dimming on the screen, and print os_log on the content screen
I have created an iOS .ipa file to run some tests, and all the test cases have os_log implemented for tracing. However, there is an issue; my tests take over 20 seconds to run, and the screen starts to dim. Consequently, the execution stops. Once I reactivate the screen, the tests resume. I added [UIApplication.sharedApplication setIdleTimerDisabled:YES]; to the code, but it doesn't resolve the problem. I've used os_log to trace all the test case results. I wonder if it's possible to display all the os_log messages from runTest on the app main screen as well. int main(int argc, char** argv) { //Separate thread to runTest, os_log implemented there std::thread thread_obj(runTests, argc, argv); int applicationReturn; @autoreleasepool { [UIApplication.sharedApplication setIdleTimerDisabled:YES]; applicationReturn = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } thread_obj.join(); [UIApplication.sharedApplication setIdleTimerDisabled:NO]; return applicationReturn; }
3
0
506
Nov ’23
Why are only @objc marked methods visible in objective C
I was going through this apple documention and it states, "By default, the generated header contains interfaces for Swift declarations marked with the public or open modifier", however, In my Xcode project, the public methods are not visible in the objective C code, and only the methods that are marked with @objc are visible. Is there some problem in my code or Is this a bug?
1
0
407
Nov ’23
Wrong Video Aspect Ratio
Hello. I'm having problems with a narrow video aspect ratio displayed on an iPad Air. In an outlet labeled ImagePreviewOutlet I want to display a video feed from the iPad camera facing the user. So basically the user will see their own face. I did all the necessary moves in the Story Board and in the code and I got what I wanted. Except it is in the wrong Aspect Ratio. The image doesn't fill the screen of the iPad even though the dimensions of the ImagePreviewOutlet does. It's narrow, showing white space on either side of the video. I want a wider aspect ratio. I understand that the iPad has 2 ratios : 4:3 and 16:9. Can anybody help me? I can supply the code that I'm using but I don't want my first post to be overwhelming. Thank you for your time. JR
1
0
442
Nov ’23
NSLog no longer sh
I use a macro to do logging: #define LOG(fmt, ...) NSLog((fmt), ##VA_ARGS); which means I can write code like: LOG(@"radius=%.1f", fRadius) Up until Xcode 15 the %.1f would be respected and display fRadius to one decimal place. But since Xcode 15 it seems to ignore that and just display all decimal places regardless. Anyone know why, and how to fix that?
4
1
545
Nov ’23
Get the number of Apple Silicon performance cores in Python
Simple question, I want to determine the number of performance cores in an Python script (better a Python app frozen with PyInstaller, which could make a difference). there are some ways to get the number of CPUs/cores like os.cpu_count(), multiprocessing.cpu_count() or psutil.cpu_count() (the later allowing discrimination between physical and virtual cores). However, Apple Silicon CPUs are separated into performance and efficiency cores, which you can get with (e.g.) sysctl hw.perflevel0.logicalcpu_max for performance and sysctl hw.perflevel1.logicalcpu_max for efficiency cores. Is there any way to get this in Python besides running sysctl and get the shell output? Maybe using the pyobjc package?
0
0
681
Nov ’23
macOS 14 - NSAttributedString created from HTML displays as "undefined character" glyphs when certain fonts are used
I allow users to choose a font to use throughout the app, then display text using that font in 3 different ways: As the default body font of an HTML document displayed in a WKWebView. Used to create an NSAttributedString then displayed in an NSTextField. Used as the body font of a very small HTML document (2-3 lines), converted to NSAttributedString, then displayed in an NSTextField. My code has been working fine for years, but starting with the release of Sonoma (macOS 14), any text that is converted from HTML to NSAttributedString displays as all "question marks in boxes" for each character. This happens when certain fonts are used. In particular I've seen it with Calibri, Candara, and SF Pro. Calibri and Candara are Microsoft fonts and I think are distributed with MS Office. SF Pro is an Apple font. There could be others; I haven't done an exhaustive check. What I can tell you is that this has been working fine literally until a couple weeks ago when customers began installing macOS 14. If they go into my app and select a different font (such as Arial or Times New Roman) everything works fine. It is only certain fonts that don't work, and those fonts work when used as the body font of an HTML document in WKWebView and when used as the font for a new NSAttributedString. They just don't work if you make a little HTML document with the font selected as the body font, then convert to NSAttributedString. Here's the code that worked up until macOS 14: NSString *htmlString = @"<!DOCTYPE html>" "<html>" "<head>" "<style>" "body { font-family: 'Candara', serif; font-size: 14px; }" "</style>" "</head>" "<body>" "This won't display right." "</body>" "</html>"; NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}; NSError *error; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:htmlData options:options documentAttributes:nil error:&error]; Note the fallback of "serif" — that doesn't matter. you get all undefined characters and the fallback font is not used. It's as if the renderer really believes the font is usable, but it isn't.
1
0
618
Nov ’23
class `NSKVONotifying_AVCapturePhotoOutput' not linked into application
I get the message "objc[29459]: class `NSKVONotifying_AVCapturePhotoOutput' not linked into application" and I do not seem to be able to process a captured photo. Users on stackoverflow are seeing this too (using Swift): https://stackoverflow.com/questions/76893120/unable-to-capture-and-save-image-using-avcapturephotooutput-in-macos-app I am running Ventura 13.0.1. Minimal example: #import <AVFoundation/AVFoundation.h> @interface PhotoCaptureDelegate : NSObject <AVCapturePhotoCaptureDelegate> @end @implementation PhotoCaptureDelegate - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(nullable NSError *)error { if (error) { NSLog(@"Error capturing photo: %@", error.localizedDescription); } else { NSLog(@"Ready to process photo."); } } @end int main(int argc, const char * argv[]) { @autoreleasepool { AVCaptureSession *captureSession = [[AVCaptureSession alloc] init]; AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; if (captureDevice) { NSError *error = nil; AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error]; if (!error) { [captureSession beginConfiguration]; [captureSession addInput:input]; AVCapturePhotoOutput *photoOutput = [[AVCapturePhotoOutput alloc] init]; [captureSession addOutput:photoOutput]; [captureSession commitConfiguration]; [captureSession startRunning]; // Create and configure a capture connection AVCaptureConnection *connection = [photoOutput connectionWithMediaType:AVMediaTypeVideo]; if (connection) { // Configure settings for the photo capture AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings]; //[photoSettings setFlashMode:AVCaptureFlashModeAuto]; // Set the flash mode if needed PhotoCaptureDelegate *photoCaptureDelegate = [[PhotoCaptureDelegate alloc] init]; [photoOutput capturePhotoWithSettings:photoSettings delegate:photoCaptureDelegate]; // Capture a photo and delegate will receive the result } } else { NSLog(@"Error adding input: %@", error.localizedDescription); } } else { NSLog(@"No video capture device available"); } } return 0; } Compile with: $ clang -framework AVFoundation -framework Foundation -o test avphoto.m Any thoughts? Best regards, Linus
1
0
536
Nov ’23
After my project is built using Xcode 15 it crashes wherever I have created cpp instance using "new" in OS 11 with arm processor systems.
I am building a project which has swift, cpp and objective - c files. Till now the app was working fine. But now Since the app is built using the newer Xcode version ie Xcode 15, the app is crashing in the BigSur( MacOS 11) using arm64 processor. It works fine in all other OS including OS 11 with x86_64 processor. When I checked the reason for the crash, the crash report points at the place where we created cpp instances in objective c file. My code is as follows _deviceList = new AudioDeviceList(false); // AudioDeviceList is the cpp class and I am creating instance for this in Objective c file mBassTrebleLevelLeft = new BassTreble(512); // BassTreble is the cpp class and I am creating instance for this in Objective c file The crash points at these lines. Can anyone please help me why there is issue with Xcode 15 on creation of cpp instance?
2
0
758
Nov ’23
Setting UIViewController preferredContentSize is broken in iOS 17
In iOS 17, I am having an issue where UIPopoverPresentationControllers are not retaining the preferred size of the UIViewController they contain. The following method uses a UIPopoverPresentationController popoverVC to display a UIViewController contentVC from a UIView view anchor location frame. + (void) showDialogiPad:(UIViewController *)contentVC fromPresentingVC:(UIViewController *)presentingVC inView:(UIView *)view atFrame:(CGRect)frame withDirection:(UIPopoverArrowDirection)direction { // Set content view controller size contentVC.preferredContentSize = contentVC.view.frame.size; // Choose the presentation style in which the content is // displayed in a popover view contentVC.modalPresentationStyle = UIModalPresentationPopover; // Get a popover presentation controller UIPopoverPresentationController *popoverVC = contentVC.popoverPresentationController; // Set the popover size and anchor location contentVC.popoverPresentationController.sourceRect = frame; contentVC.popoverPresentationController.sourceView = view; // Set the arrow direction for the popover popoverVC.permittedArrowDirections = direction; // Present the popover presentation controller [presentingVC presentViewController:contentVC animated:YES completion:nil]; } Prior to iOS 17, the code displayed the popover as expected as shown here: The issue now however is since the update to iOS 17, the popover is now squashed and displayed as: A few observations: The popover dialog actually displays properly the first time you open it. Every subsequent time you open it, it is squashed. When I comment out the line that sets the preferredContentSize, the popover opens at the max size every time - so it shows all the content but it is not set to the size I want it to be. If I leave preferredContentSize as is but change modalPresentationStyle to UIModalPresentationFormSheet, the size of the popover is correct but the popover always presents in the middle of the screen.
1
0
586
Nov ’23
Showing "Unable To Install" alert
This is enterprise application and we distribute using TestFairy for testing. Today when we upload IPA file to TestFairy and downloaded app in iPad, we are getting error showing "Unable To Install" Please try again later after installation finish. Attached screenshot for reference. This app is in Objective C. Previous versions uploaded on TestFairy working fine and able to install.
1
0
526
Nov ’23
iOS 12 NSInternalInconsistencyException An -observeValueForKeyPath:ofObject:change:context: message was received but not handled Crash
Hi, The latest version of my app has a lot of comments about An -observeValueForKeyPath:ofObject:change:context: message was received but not handled crashes.However, the codes that caused the crash have not been changed in this version. Crash log 0: NSInternalInconsistencyException &lt;CTRun: 0x1147bfd90&gt;{string range = (8, 1), string = "\u7BEE", attributes = &lt;CFBasicHash 0x280356480 [0x20dd53a30]&gt;{type = mutable dict, count = 3, entries =&gt; 0 : &lt;CFString 0x20e455978 [0x20dd53a30]&gt;{contents = "NSFont"} = &lt;CTFont: 0x1147550a0&gt;{name = PingFangSC-Regular, size = 27.000000, matrix = 0x0, descriptor = &lt;CTFontDescriptor: 0x283c31ce0&gt;{attributes = &lt;CFBasicHash 0x280225cc0 [0x20dd53a30]&gt;{type = mutable dict, count = 1, entries =&gt; 2 : &lt;CFString 0x20e45bc38 [0x20dd53a30]&gt;{contents = "NSFontNameAttribute"} = &lt;CFString 0x281730060 [0x20dd53a30]&gt;{contents = "PingFangSC-Regular"} } &gt;}} 1 : &lt;CFString 0x20ef906b0 [0x20dd53a30]&gt;{contents = "NSParagraphStyle"} = &lt;CTParagraphStyle: 0x28332e370&gt;{base writing direction = -1, alignment = 0, line break mode = 0, default tab interval = 0 first line head indent = 0, head indent = 0, tail indent = 0 line height multiple = 0, maximum line height = 0, minimum line height = 0 line spacing adjustment = 0, paragraph spacing = 0, paragraph spacing before = 0 maximum li...too long be cutted! 0 CoreFoundation ___exceptionPreprocess + 232 14 UIKitCore -[UIViewController loadView] + 256 15 *** -[SNThemeViewController loadView] (SNThemeViewController.m:52) Log1 NSInternalInconsistencyException &lt;CTFont: 0x118a0f7a0&gt;{name = .PingFangSC-Regular, size = 19.000000, matrix = 0x0, descriptor = &lt;CTFontDescriptor: 0x282b5c1e0&gt;{attributes = &lt;CFBasicHash 0x281427000 [0x21b4a9430]&gt;{type = mutable dict, count = 1, entries =&gt; 2 : &lt;CFString 0x21bb98888 [0x21b4a9430]&gt;{contents = "NSFontNameAttribute"} = &lt;CFString 0x21bb87408 [0x21b4a9430]&gt;{contents = ".PingFangSC-Regular"} } &gt;}}: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled. Key path: position Observed object: &lt;CALayer: 0x280e5e4c0&gt; Change: { kind = 1; new = "NSPoint: {207, 0.5}"; } Context: 0x0 0 CoreFoundation ___exceptionPreprocess + 228 12 UIKitCore -[UITableViewHeaderFooterView layoutSubviews] + 84 13 *** -[SNCommentCellFooter layoutSubviews] (SNCommentCellFooter.m:63) Log2 NSInternalInconsistencyException &lt;NWConcrete_nw_endpoint_flow: 0x10908f400&gt;: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled. Key path: contentOffset Observed object: &lt;UITableView: 0x1088b9a00; frame = (0 0; 428 799); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = &lt;NSArray: 0x28338cff0&gt;; backgroundColor = UIExtendedGrayColorSpace 0 0; layer = &lt;CALayer: 0x283d1d5a0&gt;; contentOffset: {0, 21781.666666666668}; contentSize: {428, 24466}; adjustedContentInset: {0, 0, 156, 0}; dataSource: &lt;SNNewsPageTableDataSource: 0x281e0b250&gt;&gt; Change: { kind = 1; new = "NSPoint: {0, 21781.666666666668}"; } Context: 0x0 0 CoreFoundation ___exceptionPreprocess + 164 21 UIKitCore _UIApplicationMain + 340 22 *** main (main.m:15) Log3 NSInternalInconsistencyException &lt;UILongPressGestureRecognizer: 0x135b942f0; state = Possible; view = &lt;UITableViewCellContentView 0x135b81f00&gt;; target= &lt;(action=_longPressGestureRecognized:, target=&lt;UITableViewCell 0x136a23200&gt;)&gt;&gt;: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled. Key path: position Observed object: &lt;CALayer: 0x281bf6180&gt; Change: { kind = 1; new = "NSPoint: {19, 19}"; } Context: 0x0 0 CoreFoundation ___exceptionPreprocess + 228 12 UIKitCore -[UIImageView _setViewGeometry:forMetric:] + 172 13 *** -[SNLikeAnimationButton layoutSubviews] (SNLikeAnimationButton.m:142) and so on... I don’t know how to locate it now. Please help me locate the problem. I look forward to your reply. If you need more information please let me know
0
0
343
Nov ’23
UIImageView not working on iOS 17
I am developing an mobile application on objective C. I use UIImageView a lot to display several images on my app. It works fine up to iOS 16. Starting on iOS 17 both on a real iPhone and on the simulators the images don't show. It is like UIImageView does not load the images on iOS17. Is there anything new on iOS17 regarding how to use UIImageView?
5
1
911
Nov ’23
Getting Error on iOS 17 for NSInternalInconsistencyException
In iOS 17 Im getting following error : Alert NSInternalinconsistencyException-UlViewController is missing its initial trait collection populated during initialization. This is a serious bug, likely caused by accessing properties or methods on the view controller before calling a UlViewController initializer. View controller: &lt;HamburgerMenuViewController: 0x11307de00&gt; It works on 16.7.1. It is a blocker in iOS 17
1
0
735
Oct ’23
Mouse events on popup menu view seem to be incorrect in Sonoma.
as I open the pop-up menu and move the mouse before that opened, MouseEntered Event and MouseExited Event are called when mouse moved. The following trackingAreas options are inclued in the view in pop-up area. NSTrackingInVisibleRect, NSTrackingMouseEnteredAndExited, NSTrackingMouseMoved, NSTrackingActiveInKeyWindow LocationInWindow of MouseExitedEvent seem to be incorrect. This problems does not occur in the following cases. Do not move the mouse until the popup is fully opened. Left mouse button down on pop-up area. Move the mouse out of the pop-up area. This issue occurs in Sonoma(MacOS14.0) and later. I would like to know if this is a code issue or a bug in the OS Version. AppDelegate.h #import &lt;Cocoa/Cocoa.h&gt; @interface ViewInPopup : NSView { NSString* resultStr; NSUInteger enteredCount; NSPoint lastEnteredPos; NSUInteger exitedCount; NSPoint lastExitedPos; NSUInteger movedCount; NSPoint lastMovedPos; NSTrackingArea* trackingArea; } @end @interface AppDelegate : NSObject &lt;NSApplicationDelegate&gt; { NSMenu* myMenu; ViewInPopup* viewInPopup; } - (IBAction)onClickButton:(id)sender; @end AppDelegate.mm #import "AppDelegate.h" @interface ViewInPopup () - (void)showResult:(NSEvent*)event; @end @implementation ViewInPopup - (id)initWithFrame:(NSRect)frameRect { self = [super initWithFrame:frameRect]; [self setWantsLayer:TRUE]; [[self layer] setBackgroundColor:[NSColor redColor].CGColor]; return self; } - (void)drawRect:(NSRect)dirtyRect { [super drawRect:dirtyRect]; [resultStr drawInRect:[self bounds] withAttributes:nil]; } - (void)updateTrackingAreas { if (trackingArea) { [self removeTrackingArea:trackingArea]; } NSTrackingAreaOptions options = NSTrackingInVisibleRect | NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveInKeyWindow; trackingArea = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil]; [self addTrackingArea:trackingArea]; [super updateTrackingAreas]; } - (void)mouseEntered:(NSEvent *)event { [self showResult:event]; [super mouseEntered:event]; } - (void)mouseExited:(NSEvent *)event { [self showResult:event]; [super mouseExited:event]; } - (void)mouseMoved:(NSEvent *)event { [self showResult:event]; [super mouseMoved:event]; } - (void)showResult:(NSEvent*)event { NSString* eventTypeStr = @""; switch (event.type) { case NSEventTypeMouseEntered: eventTypeStr = @"Entered"; [[self layer] setBackgroundColor:[NSColor redColor].CGColor]; if (enteredCount &gt;= NSUIntegerMax) { enteredCount = 0; } else { enteredCount++; } lastEnteredPos = event.locationInWindow; break; case NSEventTypeMouseExited: eventTypeStr = @"Exited"; [[self layer] setBackgroundColor:[NSColor blueColor].CGColor]; if (exitedCount &gt;= NSUIntegerMax) { exitedCount = 0; } else { exitedCount++; } lastExitedPos = event.locationInWindow; break; case NSEventTypeMouseMoved: eventTypeStr = @"Moved"; [[self layer] setBackgroundColor:[NSColor greenColor].CGColor]; if (movedCount &gt;= NSUIntegerMax) { movedCount = 0; } else { movedCount++; } lastMovedPos = event.locationInWindow; break; default: return; } resultStr = [NSString stringWithFormat:@"LastEventType:%@\n\nEnteredCount:%ld\nLastEnteredPosition:(%f, %f)\n\nExitedCount:%ld\nLastExitedPosition:(%f %f)\n\nMovedCount:%ld\nLastMovedPosition:(%f, %f)", eventTypeStr, enteredCount, lastEnteredPos.x, lastEnteredPos.y, exitedCount, lastExitedPos.x, lastExitedPos.y, movedCount, lastMovedPos.x, lastMovedPos.y]; [self setNeedsDisplay:YES]; } @end @interface AppDelegate () @property (strong) IBOutlet NSWindow *window; @end @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Insert code here to initialize your application myMenu = [[NSMenu alloc] init]; NSMenuItem* item = [[NSMenuItem alloc] init]; [myMenu addItem:item]; viewInPopup = [[ViewInPopup alloc] initWithFrame:NSMakeRect(0, 0, 300, 300)]; [item setView:viewInPopup]; } - (void)applicationWillTerminate:(NSNotification *)aNotification { // Insert code here to tear down your application } - (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app { return YES; } - (IBAction)onClickButton:(id)sender { [myMenu popUpMenuPositioningItem:nil atLocation:NSZeroPoint inView:(NSView*)sender]; } @end
2
1
918
Mar ’24
macOS: WiFi security type on Sonoma
In the context of a system utility that reports OS stats periodically, the security type for a connected WiFi network could be obtained with Core WLAN via CWInterface.security. This used to work up to Ventur; howver, after upgrading to Sonoma, cwInterface.security now returns kCWSecurityUnknown. In other posts, I have read about changes in how Core WLAN works which are related to Sonoma. How can I determine the security type for a connected WiFi network on Sonoma? It would be preferable if the suggested approach would also work on previous macOS versions as well. Many thanks in advance! :-)
2
0
962
Mar ’24