Objective-C

RSS for tag

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

Posts under Objective-C tag

223 Posts
Sort by:
Post not yet marked as solved
0 Replies
200 Views
I have a lib that I also distribute with cocoapod, and the project has both Swift and Objc code. Im using modules to expose objc private classes to Swift, but some of this private classes also have a reference to the public objc classes. Then the compiler complains about "Duplicate interface definition" This does not happen if the project is created as a framework, but I have not control how the project will be used as. Any suggestion?
Posted
by Brustolin.
Last updated
.
Post not yet marked as solved
1 Replies
259 Views
I have a document class that makes a main window for showing the data. Pieces of that data can be opened in separate subwindows for editing. When the user closes the main window and the document is dirty and the subwindows are dirty, I would like to present UI that asks the user if they want to save the changes in the subwindows (and possibly the main window if I decide to turn off autoSavesInPlace for the document). I've tried a number of possible methods of doing this, but always run into some roadblock: -Overriding shouldCloseWindowController:delegate:shouldCloseSelector:contextInfo: where I would go through the open subwindows and asking and tell them to do their own UI for asking if they should be saved. This is no good because everything returns back to the run loop and the doc would close, leaving the subwindows open with their Save? sheets up. -Making the subwindows inherit from NSEditor and registering them with the document. This looked like it would work, but it caused an infinite loop in my override of commitEditingWithDelegate:didCommitSelector:contextInfo: that I don't understand. I'm probably calling the didCommitSelector wrong because the docs aren't clear and provide no example. -Adding each subwindow's NSWindowController to the document's windowControllers list. I don't recall the problems this caused. Any sage advice about this? Possible examples? The Document is Swift, the subwindows are Cocoa, so examples in either language is fine.
Posted
by sjmills.
Last updated
.
Post not yet marked as solved
2 Replies
771 Views
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 <Cocoa/Cocoa.h> @interface ViewInPopup : NSView { NSString* resultStr; NSUInteger enteredCount; NSPoint lastEnteredPos; NSUInteger exitedCount; NSPoint lastExitedPos; NSUInteger movedCount; NSPoint lastMovedPos; NSTrackingArea* trackingArea; } @end @interface AppDelegate : NSObject <NSApplicationDelegate> { 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 >= NSUIntegerMax) { enteredCount = 0; } else { enteredCount++; } lastEnteredPos = event.locationInWindow; break; case NSEventTypeMouseExited: eventTypeStr = @"Exited"; [[self layer] setBackgroundColor:[NSColor blueColor].CGColor]; if (exitedCount >= NSUIntegerMax) { exitedCount = 0; } else { exitedCount++; } lastExitedPos = event.locationInWindow; break; case NSEventTypeMouseMoved: eventTypeStr = @"Moved"; [[self layer] setBackgroundColor:[NSColor greenColor].CGColor]; if (movedCount >= 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
Posted
by nwj.
Last updated
.
Post not yet marked as solved
14 Replies
2.0k Views
Hi, An existing app on AppStore have issue with SHA256 Hash only since iOS17.4. And only Pro and Pro Max seems affected by this issue. NSData is read from downloaded file. Hash is calculated with unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md) And compared with original HASH It appears different only on iOS17.4 and only Pro and Pro Max. But i can't reproduce this issue. Do you have an idea ? Thank you
Posted
by GB_fr.
Last updated
.
Post not yet marked as solved
5 Replies
4.3k Views
Hi there, I'm working on an app that contains a mini system monitoring utility. I would like to list the top CPU-using processes. As Quinn “The Eskimo!” has repeatedly cautioned, relying on private frameworks is just begging for maintenance effort in the future. Ideally, I want to go through public headers/frameworks. I've gone to great lengths to try to find this information myself, and at this point I'm just struggling. I detail my research below. Any pointers in the right direction would be much appreciated! Attempts Libproc First I looked at libproc. Using proc_pidinfo with PROC_PIDTHREADINFO, I'm able to get each thread of an app, with its associated CPU usage percentage. Summing these, I could get the total for an app. Unfortunately, this has two downsides: Listing a table of processes now takes O(proces_count) rather than just O(process_count), and causes way more syscalls to be made It doesn't work for processes owned by other users. Perhaps running as root could alleviate that, but that would involve making a priviliedged helper akin to the existing sysmond that Activity Monitor.app uses. I'm a little scared of that, because I don't want to put my users at risk. Sysctl Using the keys [CTL_KERN, KERN_PROC, KERN_PROC_PID, someProcessID], I'm able to get a kinfo_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/sysctl.h#L750-L776 instance. Accessing its .kp_proc - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L96-L150.p_pctcpu - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/proc.h#L123 looked really promising, but that value is always zero. Digging deeper, I found the kernel code that fills this struct in (fill_user64_externproc - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1121-L1168). The assignment of p_pctcpu - https://github.com/apple-opensource/xnu/blob/c76cff20e09b8d61688d1c3dfb8cc855cccb93ad/bsd/kern/kern_sysctl.c#L1149 is in a conditional region, relying on the _PROC_HAS_SCHEDINFO_ flag. Disassembling the kernel on my mac, I could confirm that the assignment of that field never happens (thus _PROC_HAS_SCHEDINFO_ wasn't set during compilation, and the value will always stay zero) Reverse engineering Activity Monitor.app Activity Monitor.app makes proc_info and sysctl system calls, but from looking at the disassembly, it doesn't look like that's where its CPU figures come from. From what I can tell, it's using private functions from /usr/lib/libsysmon.dylib. That's a user library which wraps an XPC connection to sysmond (/usr/libexec/sysmond), allowing you to create requests (sysmon_request_create), add specific attributes you want to retrieve (sysmon_request_add_attribute), and then functions to query that data out (sysmon_row_get_value). Getting the data "striaght from the horses mouth" like this sounds ideal. But unfortunately, the only documentation/usage I can find of sysmond is from bug databases demonstrating a privilege escalation vulnerability lol. There are some partial reverse engineered header files floating around, but they're incomplete, and have the usual fragility/upkeep issues associated with using private APIs. On one hand, I don't want to depend on a private API, because that takes a lot of time to reverse engineer, keep up with changes, etc. On the other, making my own similar privileged helper would be duplicating effort, and expose a bigger attack surface. Needless to say, I have no confidence in being able to make a safer privileged helper than Apple's engineers lol Reverse engineering iStat Menus Looks like they're using proc_pid_rusage - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/libsyscall/wrappers/libproc/libproc.h#L103-L108 . However, I don't know how to convert the cpu_*_time fields of the resulting struct rusage_info_v4 - https://github.com/apple-opensource/xnu/blob/24525736ba5b8a67ce3a8a017ced469abe101ad5/bsd/sys/resource.h#L306-L343 to compute a "simple" percentage. Even if I came up with some formula that produces plausible looking results, I have no real guarantee it's correct or equivalent to what Activity Monitor shows.
Posted Last updated
.
Post not yet marked as solved
0 Replies
217 Views
Does "natural scrolling" system preference affect NSEvent.scrollingDeltaY? BTW, I find that "natural scrolling" on my Sonoma (Mac mini m1) stops working; turning on/off has no effect when I scroll in Finder app.
Posted
by imneo.
Last updated
.
Post not yet marked as solved
1 Replies
316 Views
I have an uncommon scenario here. outer tableview +--------------------------+ | column 1| inner tableview| +--------------------------+ Now most often the out tableview has many rows and vertical scrollbar visible. When user try to scroll vertically in the inner tableview but it has no vertical scrollbar (because it has only a few items), I want the scroll event sink into its parent view or better outer tableview, so that user does not have to move cursor to first column in outer tableview and scrolls. Is this possible?
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
223 Views
To me, the documentation for this method is not at all clear and needs to provide sample code. I tried searching the dev site for sample projects, but they're no longer where they lived for decades before. And where's the TextEdit sample project?! I need to override shouldCloseWindowController so I can make sure some sub-windows can be closed before closing the document's one and only window. I've done that, but then have no idea what I'm supposed to do to all the document to close. I tried this, which is what I think the NSDocument version header says to do: if ((self.windowControllers.first?.shouldCloseDocument) != nil){ self.canClose(withDelegate:delegate as Any, shouldClose:shouldCloseSelector, contextInfo:contextInfo); } But the document never gets the close() method called - only the window goes away.
Posted
by sjmills.
Last updated
.
Post not yet marked as solved
2 Replies
749 Views
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! :-)
Posted
by fsauter.
Last updated
.
Post not yet marked as solved
0 Replies
225 Views
Hi, I have implemented VOIP calling feature in my application using OpenTok SDK and CallKit framework. Calling feature is working most of the time. But there is one strange issue I have come across. During a call, if any external cellular call appears and if I decline that external call then my running voip call also disconnects. This is happening some of the iPhone devices. iPhone config: Model: iPhone 11 iOS Version: 17.3 I have added loggers CXEndCallAction and -provider:performEndCallAction and debugged at my end. I found that CXEndCallAction is not executing from my end but still -provider:performEndCallAction is triggered by iOS along with my ongoing callUUID. This is very strange behaviour I am observing in one of my iPhone device. I have tested this in 4 iPhone devices but i am facing this issue only in 1 iPhone. Thanks,
Posted Last updated
.
Post marked as solved
1 Replies
327 Views
I have a custom Objective-C ObjectCache class that utilized NSMutableDictionary to store named objects (specifically large NSImage objects). The class has a maxItems property and clear method, which worked fine. - (void)clear { @synchronized(_cache) { [_cache removeAllObjects]; } } But yesterday I received a customer feedback complaining one of my app consumes up to 24GB memory. I verified that on my M1 Mac mini, and it's true. Even after calling clear method, memory usage shown in both Xcode debugger panel and Activity Monitor remains the same. It did work before. Once I close a picture gallery window by calling clear method, memory usage dropped immediately as shown in Activity Monitor. I suspect that this is a bug in ARM architecture. Does anyone else have same problem?
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
313 Views
I'm currently using a WKWebView to load certain types of documents via loadRequest, but I've recently been running into an issue with .doc files doing this: static NSString *customScheme = @"customscheme"; @interface WordDocWKSchemeHandler : NSObject <WKURLSchemeHandler> @end @implementation WordDocWKSchemeHandler { NSData *_data; NSString *_mimeType; } - (instancetype)initWithData:(NSData*)data mimeType:(NSString*)mimeType{ self = [super init]; if (self) { _data = data; _mimeType = mimeType; } return self; } - (void)webView:(WKWebView *)webView startURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask { NSURL *url = urlSchemeTask.request.URL; if (![url.scheme isEqualToString:customScheme]){ return; } NSURLResponse *response = [[NSURLResponse alloc] initWithURL:url MIMEType:_mimeType expectedContentLength:_data.length textEncodingName:@""]; [urlSchemeTask didReceiveResponse:response]; [urlSchemeTask didReceiveData:_data]; [urlSchemeTask didFinish]; } - (void)webView:(WKWebView *)webView stopURLSchemeTask:(id<WKURLSchemeTask>)urlSchemeTask{ //empty } @end - (void)_setupWebViewPropertiesAndConstraints{ _webView.navigationDelegate = self; _webView.hidden = YES; [self.view addConstrainedSubview:_webView]; [self.view addConstraints:[_webView constraintsForFillingSuperview]]; self.container.showsLoadingIndicator = YES; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; WKWebViewConfiguration *docConfig = [WKWebViewConfiguration new]; WordDocWKSchemeHandler *schemeHanlder = [[WordDocWKSchemeHandler alloc] initWithData:_content.data mimeType:_content.contentType]; [docConfig setURLSchemeHandler:schemeHanlder forURLScheme:customScheme]; //Setup webview with custom config handler _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:docConfig]; [self _setupWebViewPropertiesAndConstraints]; NSURL *customURL = [NSURL URLWithString:[NSString stringWithFormat:@"\%@:/",customScheme]]; [_webView loadRequest:[NSURLRequest requestWithURL:customURL]]; } The mimeType is correctly being resolved to "application/msword" but any time we try to load this the navigation fails: -(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { The error message here is OfficeImportErrorDomain Code=912. I've tried this on both a simulator and actual device on iOS 17 and 16 and this always fails. I've also tried turning the data into a base64 string and loading it that way and this also fails. Any advice here would be appreciated. It seems like this used to work at some point but no longer works.
Posted Last updated
.
Post not yet marked as solved
0 Replies
245 Views
Hello, I have some older objective-c projects that are about creating reports of tables and gantt charts and printing those reports. They work fine on Ventura and BigSur, but after upgrading to Sonoma, I encountered some problems with the Print dialog and options. Specifically, the page preview is not working, and the Close button does not close the dialog and is not responsive. I have to force quit the app to exit the Print dialog. This makes it impossible to print my reports properly. I wonder if this is a bug with Sonoma or with objective-c, and if there is any workaround or fix for this issue. I appreciate any help or advice from the community or the Apple support team. Thank you.
Posted
by _Filip_.
Last updated
.
Post not yet marked as solved
7 Replies
390 Views
I have an app which uses Cocoa Pods to use MQTTClient in connecting to io.adafruit. I use the app to get the various data point stored at io.adafruit and to even send data to adafruit to control a connected unit. I am using .xcworkspace to upload the app on my phone and everything works fine. I am hoping to wake my app every so ofter to get some data points from io.adafruit and if certain conditions exist, I want to send a notification to the user. I have added Background Modes to my app's Signing & Capabilities (Background fetch) and in my INFO I have Permitted background task scheduler identifiers with the String identifier LEVELIT.Refresh. The following is my code I am using in my AppDelegate.h #import <UIKit/UIKit.h> #import <CoreData/CoreData.h> #import <MQTTClient/MQTTClient.h> #import <UserNotifications/UserNotifications.h> @interface AppDelegate: UIResponder <UIApplicationDelegate, UNUserNotificationCenterDelegate,UIAlertViewDelegate,MQTTSessionDelegate>{ MQTTSession *session3; } @property (nonatomic, retain) MQTTSession *session3; @property (nonatomic, strong) NSPersistentContainer *persistentContainer; @end And this is the code I use in my AppDelegate.m #import "AppDelegate.h" #import <BackgroundTasks/BackgroundTasks.h> #import <CloudKit/CloudKit.h> #import <UserNotifications/UserNotifications.h> static NSString* TaskID = @"LEVELIT.refresh"; @interface AppDelegate() @property (nonatomic, retain) NSString *myUserName; @property (nonatomic, retain) NSString *myUserKey; @property (nonatomic, retain) NSString *myTrips; @property (nonatomic, retain) NSString *atrip; @property (nonatomic, retain) NSString *trip; @property (nonatomic, retain) NSString *gettrip; @property(strong) void (^expirationHandler)(void); @end @implementation AppDelegate @synthesize session3,window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (@available(iOS 13.0, *)) { [[BGTaskScheduler sharedScheduler] registerForTaskWithIdentifier:TaskID usingQueue:nil launchHandler:^(BGAppRefreshTask *task) { [self handleAppRefreshTask:task]; }]; } else { // Fallback on earlier versions } UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) { }]; UNNotificationCategory* generalCategory = [UNNotificationCategory categoryWithIdentifier:@"GENERAL" actions:@[] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction]; NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults]; if([[[defaults2 dictionaryRepresentation] allKeys] containsObject:@"myUserNameFile"]){ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.myUserName = [defaults objectForKey:@"myUserNameFile"]; NSLog(@"myUserName1:%@",self.myUserName); self.myUserKey = [defaults objectForKey:@"myUserKeyFile"]; NSLog(@"myUserKey1:%@",self.myUserKey); } return YES; } } -(void)schedualLocalNotifications{ } - (void)setTaskCompletedWithSuccess:(BOOL)success;{ NSLog(@"Completed"); } - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"Entering background"); if (@available(iOS 13.0, *)) { BGAppRefreshTaskRequest *request = [[BGAppRefreshTaskRequest alloc] initWithIdentifier:TaskID]; request.earliestBeginDate = [NSDate dateWithTimeIntervalSinceNow:15*60]; NSError *error; BOOL success = [[BGTaskScheduler sharedScheduler] submitTaskRequest:request error:&error]; if (success == TRUE) { } } //BREAKPOINT } -(void)handleAppRefreshTask:(BGAppRefreshTask *)task API_AVAILABLE(ios(13.0)){ //do things with task NSLog(@"Process started!"); task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; MQTTCFSocketTransport *transport = [[MQTTCFSocketTransport alloc] init]; transport.host = @"io.adafruit.com"; transport.port = 1883; self.session3 = [[MQTTSession alloc] init]; self.session3.userName = self.myUserName; self.session3.password = self.myUserKey; self.session3.transport = transport; self.session3.delegate = self; self.session3.keepAliveInterval = 30; // new stuff NSString *feeds = [self.myUserName stringByAppendingString:@"/feeds/"]; self.atrip = [feeds stringByAppendingString:@"trip"]; self.gettrip = [self.atrip stringByAppendingString:@"/get"]; [session3 connectWithConnectHandler:^(NSError *error) { if(!error){ [self.session3 subscribeToTopic:self.atrip atLevel:1 subscribeHandler:^(NSError *error, NSArray *gQoss){ if (error) { NSLog(@"Subscription failed %@", error.localizedDescription); } else { NSLog(@"Subscription sucessfull! Granted Qos: %@", gQoss); NSData* data = [@"0" dataUsingEncoding:NSUTF8StringEncoding]; [self.session3 publishData:data onTopic:self.gettrip retain:NO qos:0 publishHandler:nil]; } }]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(45* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [task setTaskCompletedWithSuccess:YES]; }); self.session3.keepAliveInterval =30; } else {NSLog(@"[connectWithConnectHandler]Error Connect %@", error.localizedDescription);} }]; task.expirationHandler = ^{ NSLog(@"WARNING: expired before finish was executed."); }; } } } //More code here but too much. @end I am not sure about the local notification because the BGAppRefreshTask is not working. I have placed a breakpoint just after the app enters background and the TASK is submitted. Then I type in e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"LEVELIT.refresh"] The app launches in the background but I get an error error: Header search couldn't locate module MQTTClient error: couldn't install checkers, unknown error Message from debugger: Terminated due to signal 9 When I tried running the app without .xcworkspace the project said it couldn't find MQTTClient. But with the workspace everything works fine. Why would launching the app in the background cause the app not to locate the MQTTClient libraries? And how do I work around this problem? Any and all help would be appreciated.
Posted
by gbenna.
Last updated
.
Post not yet marked as solved
2 Replies
294 Views
Configuration: I have a NSTextField (multiline) inside an NSWindow. I have another NSTextField (single line) inside an NSBox (which is in the same window). The multiline text field is first responder and is editing. I click on the single line text field inside the NSBox to edit that one. The NSWindow just closes. This is on Sonoma 14.2.1. I subclassed NSWindow and override the close method and put a breakpoint. Here's the call stack that leads to the window suddenly closing: #1 0x0000000189c73d90 in -[NSWindow __close] () #2 0x000000032343 in -[NSApplication(NSResponder) sendAction:to:from:] () #3 0x0000000189b543ac in -[NSControl sendAction:to:] () #4 0x0000000189b542f0 in __26-[NSCell _sendActionFrom:]_block_invoke () #5 0x0000000189b54218 in -[NSCell _sendActionFrom:] () #6 0x0000000189b5413c in -[NSButtonCell _sendActionFrom:] () #7 0x0000000189c4c508 in __29-[NSButtonCell performClick:]_block_invoke () #8 0x0000000189c4c264 in -[NSButtonCell performClick:] () #9 0x0000000189b545a8 in -[NSApplication(NSResponder) sendAction:to:from:] () #10 0x0000000189b543ac in -[NSControl sendAction:to:] () #11 0x0000000189befb48 in -[NSTextField textDidEndEditing:] () #12 0x0000000__CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ () #13 0x000000018625c65c in ___CFXRegistrationPost_block_invoke () #14 0x000000018625c5a4 in _CFXRegistrationPost () #15 0x00000001861971dc in _CFXNotificationPost () #16 0x0000000187289ff0 in -[NSNotificationCenter postNotificationName:object:userInfo:] () #17 0x0000000189bef754 in -[NSTextView(NSSharing) resignFirstResponder] () #18 0x0000000189a9fab8 in -[NSWindow _realMakeFirstResponder:] () #19 0x0000000189b4f18c in -[NSWindow(NSEventRouting) _handleMouseDownEvent:isDelayedEvent:] () #20 0x0000000189ada79c in -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] () #21 0x0000000189ada45c in -[NSWindow(NSEventRouting) sendEvent:] () #22 0x000000018a1879f4 in -[NSApplication(NSEventRouting) sendEvent:] () #23 0x0000000189dd6908 in -[NSApplication _handleEvent:] () #24 0x00000001899a1d74 in -[NSApplication run] () The mouse click is no where near the close button in the title bar.
Posted Last updated
.
Post not yet marked as solved
1 Replies
325 Views
Im honestly a bit lost and looking for general pointers. Here is the general flow of my project. I have an Xcode project where I want to return and convert the temperature values accessed from the apple smc and I found a GitHub repo with all the smc key sensors for the M3Pros/Max chips: https://github.com/exelban/stats/issues/1703 basically, I have all these keys stored in an array in obj-c like so: NSArray *smcKeys = @[ @"Tp01", @"Tp05", @"Tp09", @"Tp0D", @"Tp0b", @"Tp0f", @"Tp0j", @"Tp0n",@"Tp0h", @"Tp0L", @"Tp0S", @"Tp0V", @"Tp0z", @"Tp0v", @"Tp17", @"Tp1F", @"Tp1J", @"Tp1p", @"Tp1h", @"Tp1R", ]; I am passing all these keys by passing 'smcKeys' in a regular C code file I have here that is meant to open, close and read the data shown here: #include "smc.h" #include <mach/mach.h> #include <IOKit/IOKitLib.h> #include "smckeys.h" io_connect_t conn; kern_return_t openSMC(void) { kern_return_t result; kern_return_t service; io_iterator_t iterator; service = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("AppleSMC"), &iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } kern_return_t readSMC(char *smcKeys, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)smcKeys; SMCVal_t inputStruct; SMCVal_t outputStruct; inputStruct.datasize = sizeof(SMCVal_t); inputStruct.datatype = 'I' << 24; //a left shift operation. turning the I into an int by shifting the ASCII value 24 bits to the left inputStruct.data[0] = keyCode; result = IOConnectCallStructMethod(conn, 5, &inputStruct, sizeof(SMCVal_t), &outputStruct, (size_t*)&inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -> datasize > 0) { if (val -> datatype == ('f' << 24 | 'l' << 16 | 't' << 8 )) { //bit shifting to from 32bit operation associated with the ASCII charecters'f', 'l', and 't', sets datatype field. double temp = *(double *)val -> data; return temp; } } } return 0.0; } Which I am then then calling the functions from this file in a swift file and converting the values to Fahrenheit but no data is being printed in my console: import IOKit public class getTemperature { public struct SMCVal_t { var datasize: UInt32 var datatype: UInt32 var data: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) } @_silgen_name("openSMC") func openSMC() -> kern_return_t @_silgen_name("closeSMC") func closeSMC() -> kern_return_t @_silgen_name("readSMC") func readSMC(key: UnsafePointer<CChar>?,val: UnsafeMutablePointer<SMCVal_t>) -> kern_return_t func convertAndPrintTempValue(key:UnsafePointer<CChar>?,scale: Character, showTemp: Bool ) -> kern_return_t { let openSM = openSMC() guard openSM == 0 else { print("Failed to open SMC: \(openSM)") return kern_return_t() } let closeSM = closeSMC() guard closeSM == 0 else { print("could not close SMC: \(closeSM)") return IOServiceClose(conn) } func convertAndPrint(val: SMCVal_t) -> Double { if val.datatype == (UInt32("f".utf8.first!) << 24 | UInt32("l".utf8.first!) << 16 | UInt32("t".utf8.first!) << 8) { let extractedTemp = Double(val.data.0) return( extractedTemp * 9.0 / 5.0 + 32.0 ) } return 0.0 } let smcValue = SMCVal_t(datasize: 0, datatype: 0, data: (0,0,0,0,0,0,0,0)) let convertedVal = convertAndPrint(val: smcValue) print("Temperarure:\(convertedVal)F°") return kern_return_t() } } I know this is a lot but I am honestly looking for any tips to fill in any gaps in my knowledge for anyone who's built a similar application meant to extract any sort of data from Mac hardware.
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
1 Replies
324 Views
I have a sandboxed app in /Applications. I'm attempting to shoot a problem with LLDB, so I cd to /Applications/app-name/Contents/MacOS and do lldb programname. However, once I fire it off with "r" it dies instantly with: error: process exited with status -1 (lost connection) Should this work? Should I try signing the lldb executable? Thanks!
Posted Last updated
.
Post not yet marked as solved
2 Replies
350 Views
Because my MacOS app has a user-programmable interface, my coding creates lots of interface elements programmatically. Soon after an update to MacOS 14.3.1, I found some of these element (NSTextFields) did not draw correctly. I had not changed any code but the appearance changed for the worse (the text in the text field did not appear). I then noticed: The problem occurs when I compile in XCode 15.2 (15C500b) Version and run on computer with Sonoma 14.3.1 (23D60) If I instead compile in XCode Version 14.1 (14B47b) on Ventura 13.0.1 (22A400) and copy the app to my computer with Sonoma 14.3.1 (23D60)all works as expected. These results seem to imply XCode 15.2 does not compile correctly? Is this known issue or is there a fix?
Posted Last updated
.