My project use manual reference counting and crash with UIAlertController when touch to Action Button:
UIAlertController alert = [[UIAlertController
alertControllerWithTitle:@"fsđs"
message:@"fsđs"
preferredStyle:UIAlertControllerStyleAlert
]autorelease];
UIAlertAction actionOk = [UIAlertAction actionWithTitle:@"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:actionOk];
[self.window.rootViewController presentViewController:alert animated:YES
completion:^{
}];
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
Objective-C
RSS for tagObjective-C is a programming language for writing iOS, iPad OS, and macOS apps.
Posts under Objective-C tag
127 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
Hello we have created a function that is expanding copy module to support html format. Everything inside that function works fine but on 17.4+ IOS version copying the html element strike-through tag is not working (other HTML elements are working fine) . Looking the logs seems like are getting stripped. Also list that have indents won't work on paste indent is missing. Here is the code:
void copyToClipboard(NSString *htmlContent) {
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
[pasteboard setValue:htmlContent forPasteboardType:@"public.html"];
}
Does anyone know fix for this or when this will be fixed or will it be fixed in next update?
I am working with a React Native application that needs CPU usage data for debugging in a Production Release. Currently the module I wrote works for development but when the application is built for release that specific module errors out. I need help with configuring my Xcode project to include this module when building for release
I have a simple cocoa project, it has the default files like AppDelegate.m, AppDelegate.h , ViewController.h and ViewController.m what I want is to set the Window title to the dimension of the current window and update it as the user resizes it.
My Storyboard has an Application Scene, a Window Controller Scene and a test Scene which contains my view:
how do I go about this? should my ViewController or AppController implement NSWindowDelegate ?
I have an application with storyboard and I'm trying to set a constraint for the minimum size of my window (the view), but now matter what I do the constraint window is always grayed out, how do I go about this?
Hello,
PMSessionValidatePrintSettings return always "false" on macOS
PMPrintSettings settings;
PMPrintSession session;
Boolean result;
PMCreateSession(&session);
PMSessionSetCurrentPMPrinter(session, printer);
PMCreatePrintSettings(&settings);
PMSessionDefaultPrintSettings(session, settings);
PMSetDuplex(settings, kPMDuplexTumble);
PMSessionValidatePrintSettings(session, settings, &result);
PMRelease(session);
PMRelease(settings);
if (result) NSLog (@"%@", @"changed");
else NSLog (@"%@", @"not changed");
Thanks
After upgrading to Xcode16RC, in an old project based on ObjC, I directly used the following controller code in AppDelegate:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIButton *b = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 44, 44)];
[b setTitle:@"title" forState:UIControlStateNormal];
[self.view addSubview:b];
[b addTarget:self action:@selector(onB:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)onB:(id)sender{
PHPickerConfiguration *config = [[PHPickerConfiguration alloc]initWithPhotoLibrary:PHPhotoLibrary.sharedPhotoLibrary];
config.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent;
config.selectionLimit = 1;
config.filter = nil;
PHPickerViewController *picker = [[PHPickerViewController alloc]initWithConfiguration:config];
picker.modalPresentationStyle = UIModalPresentationFullScreen;
picker.delegate = self;
[self presentViewController:picker animated:true completion:nil];
}
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results{
}
Environment: Simulator iPhone 15 Pro (iOS18)
Before this version (iOS17.4), clicking the button to pop up the system photo picker interface was normal (the top boundary was within the SafeAreaGuide area), but now the top boundary of the interface aligns directly to the top of the window, and clicking the photo cell is unresponsive.
If I create a new Target, using the same codes, the photo picker page does not have the above problem.
Therefore, I suspect it may be due to the old project’s .proj file’s info.plist, buildSetting, or buildPhase lacking some default configuration key value required by the new version, (My project was built years ago may be from iOS13 or earlier ) but I cannot confirm the final cause.
iOS18.0 has the additional messages:
objc[79039]: Class UIAccessibilityLoaderWebShared is implemented in both /Library/Developer/CoreSimulator/Volumes/iOS_22A3351/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/WebCore.axbundle/WebCore (0x198028328) and /Library/Developer/CoreSimulator/Volumes/iOS_22A3351/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/AccessibilityBundles/WebKit.axbundle/WebKit (0x1980fc398). One of the two will be used. Which one is undefined.
AX Safe category class 'SLHighlightDisambiguationPillViewAccessibility' was not found!
Has anyone encountered the same issue as me?
So I have this program that displays events on the window using NSWindow and a NSTextField. Basically it tracks the mouse position and the keyboard state.
I created a simple class named MyEventWindow:
//
// MyEventWindow.h
// AppTest
#ifndef MyEventWindow_h
#define MyEventWindow_h
@interface MyEventWindow : NSWindow
{
}
@property(nonatomic, strong) NSTextField* label;
@property(nonatomic, strong) NSString* labelText;
- (BOOL)windowShouldClose:(id)sender;
- (instancetype) init;
- (void) setLabelText:(NSString *)labelText;
@end
@implementation MyEventWindow
-(instancetype) init
{
self = [super initWithContentRect:NSMakeRect(100, 100, 300, 300)
styleMask:(NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable)
backing:NSBackingStoreBuffered
defer:NO];
if( !self )
{
return nil;
}
[self setTitle: @"Event tracker"];
[self setIsVisible: YES];
_label = [[NSTextField alloc] initWithFrame:NSMakeRect(5, 100, 290, 100)];
[_label setBezeled: NO];
[_label setDrawsBackground: NO];
[_label setEditable: NO];
[_label setSelectable: YES];
NSFont *currentFont = [_label font];
NSFont *resizedFont = [NSFont fontWithName:[currentFont fontName] size:18];
NSFont *boldFont = [[NSFontManager sharedFontManager] convertFont:resizedFont toHaveTrait:NSFontBoldTrait];
// convert the bold font to have the italic trait
NSFont *boldItalicFont = [[NSFontManager sharedFontManager] convertFont:boldFont toHaveTrait:NSFontItalicTrait];
[_label setFont:boldItalicFont];
[_label setTextColor:[NSColor colorWithSRGBRed:0.0 green:0.5 blue:0.0 alpha:1.0]];
// attach label to the damn window
[[self contentView] addSubview: _label];
return self;
}
-(BOOL)windowShouldClose:(id)sender
{
return YES;
}
-(void) setLabelText:(NSString *)newText
{
[_label setStringValue: newText];
}
@end
#endif /* MyEventWindow_h */
Then in the main file I try to handle event loop manually:
//
// main.m
#import <Cocoa/Cocoa.h>
#import "MyEventWindow.h"
NSString* NSEventTypeToNSString(NSEventType eventType);
NSString* NSEventModifierFlagsToNSString(NSEventModifierFlags modifierFlags);
int main(int argc, char* argv[])
{
@autoreleasepool
{
[NSApplication sharedApplication];
MyEventWindow* eventWindow = [[MyEventWindow alloc] init];
[eventWindow makeKeyAndOrderFront:nil];
NSString* log = [NSString string];
// my own message loop
[NSApp finishLaunching];
while (true)
{
@autoreleasepool
{
NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny untilDate: [NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
log = [NSString stringWithFormat:@"Event [type=%@ location={%d, %d} modifierFlags={%@}]", NSEventTypeToNSString([event type]), (int)[event locationInWindow].x, (int)[event locationInWindow].y, NSEventModifierFlagsToNSString([event modifierFlags])];
//NSLog(@"log: %@", log);
[eventWindow setLabelText: log];
[NSApp sendEvent:event];
//[NSApp updateWindows]; // redundant?
}
}
}
return 0;
}
NSString* NSEventTypeToNSString(NSEventType eventType)
{
switch (eventType)
{
case NSEventTypeLeftMouseDown: return @"LeftMouseDown";
case NSEventTypeLeftMouseUp: return @"LeftMouseUp";
case NSEventTypeRightMouseDown: return @"RightMouseDown";
case NSEventTypeRightMouseUp: return @"RightMouseUp";
case NSEventTypeMouseMoved: return @"MouseMoved";
case NSEventTypeLeftMouseDragged: return @"LeftMouseDragged";
case NSEventTypeRightMouseDragged: return @"RightMouseDragged";
case NSEventTypeMouseEntered: return @"MouseEntered";
case NSEventTypeMouseExited: return @"MouseExited";
case NSEventTypeKeyDown: return @"KeyDown";
case NSEventTypeKeyUp: return @"KeyUp";
case NSEventTypeFlagsChanged: return @"FlagsChanged";
case NSEventTypeAppKitDefined: return @"AppKitDefined";
case NSEventTypeSystemDefined: return @"SystemDefined";
case NSEventTypeApplicationDefined: return @"ApplicationDefined";
case NSEventTypePeriodic: return @"Periodic";
case NSEventTypeCursorUpdate: return @"CursorUpdate";
case NSEventTypeScrollWheel: return @"ScrollWheel";
case NSEventTypeTabletPoint: return @"TabletPoint";
case NSEventTypeTabletProximity: return @"TabletProximity";
case NSEventTypeOtherMouseDown: return @"OtherMouseDown";
case NSEventTypeOtherMouseUp: return @"OtherMouseUp";
case NSEventTypeOtherMouseDragged: return @"OtherMouseDragged";
default:
return [NSString stringWithFormat:@"%lu", eventType];
}
}
NSString* NSEventModifierFlagsToNSString(NSEventModifierFlags modifierFlags)
{
NSString* result = @"";
if ((modifierFlags & NSEventModifierFlagCapsLock) == NSEventModifierFlagCapsLock)
result = [result stringByAppendingString:@"CapsLock, "];
if ((modifierFlags & NSEventModifierFlagShift) == NSEventModifierFlagShift)
result = [result stringByAppendingString:@"NShift, "];
if ((modifierFlags & NSEventModifierFlagControl) == NSEventModifierFlagControl)
result = [result stringByAppendingString:@"Control, "];
if ((modifierFlags & NSEventModifierFlagOption) == NSEventModifierFlagOption)
result = [result stringByAppendingString:@"Option, "];
if ((modifierFlags & NSEventModifierFlagCommand) == NSEventModifierFlagCommand)
result = [result stringByAppendingString:@"Command, "];
if ((modifierFlags & NSEventModifierFlagNumericPad) == NSEventModifierFlagNumericPad)
result = [result stringByAppendingString:@"NumericPad, "];
if ((modifierFlags & NSEventModifierFlagHelp) == NSEventModifierFlagHelp)
result = [result stringByAppendingString:@"Help, "];
if ((modifierFlags & NSEventModifierFlagFunction) == NSEventModifierFlagFunction)
result = [result stringByAppendingString:@"Function, "];
return result;
}
in main I added a second @autoreleasepool inside the while loop it seemed to decrease memory usage significanly, however if I keep moving my mouse a lot the memory usage will still increase.
I don't think this should be happening since the labelText is being destroying and recreated each iteration, is something wrong with my code? Why do I have a memory leak here?
Any feedback regarding the code is also appreciated
Cheers
I created a simple application which displays a window with a sample text and I'm supposed to use an alert when the user chooses to close the application, if he presses ok in the alert the application will close, if he presses cancel it goes on.
So pretty simple code, I have a window class:
//
// MyWindow.h
// AppTest
//
// Created by sanya on 11/09/24.
//
#ifndef MyWindow_h
#define MyWindow_h
@interface Window : NSWindow
{
NSTextField* label;
}
- (instancetype)init;
- (BOOL)windowShouldClose:(id)sender;
@end
@implementation Window
-(instancetype)init
{
label = [[[NSTextField alloc] initWithFrame:NSMakeRect(5, 100, 290, 100)] autorelease];
[label setStringValue:@"Hello, World!"];
[label setBezeled:NO];
[label setDrawsBackground:NO];
[label setEditable:YES];
[label setSelectable:YES];
[label setTextColor:[NSColor colorWithSRGBRed:0.0 green:0.5 blue:0.0 alpha:1.0]];
[label setFont:[[NSFontManager sharedFontManager] convertFont:[[NSFontManager sharedFontManager] convertFont:[NSFont fontWithName:[[label font] fontName] size:45] toHaveTrait:NSFontBoldTrait] toHaveTrait:NSFontItalicTrait]];
[super initWithContentRect:NSMakeRect(0, 0, 300, 300) styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO];
[self setTitle:@"Hello world (label)"];
[[self contentView] addSubview:label];
[self center];
[self setIsVisible:YES];
return self;
}
- (BOOL)windowShouldClose:(id)sender
{
BOOL bClose = NO;
CFOptionFlags responseFlags = 0;
// Display the alert
CFUserNotificationDisplayAlert(
0,
kCFUserNotificationNoteAlertLevel,
NULL,
NULL,
NULL,
CFSTR("Alert Title"),
CFSTR("This is a message displayed in the alert."),
CFSTR("OK"),
CFSTR("Cancel"),
NULL,
&responseFlags
);
if (responseFlags == kCFUserNotificationDefaultResponse)
{
NSLog(@"User clicked OK");
bClose = YES;
}
else if (responseFlags == kCFUserNotificationAlternateResponse)
{
NSLog(@"User clicked Cancel");
}
if( bClose )
[NSApp terminate:sender];
return bClose;
}
@end
#endif /* MyWindow_h */
And in the main function I just initialize it:
int main(int argc, const char * argv[])
{
[NSApplication sharedApplication];
[[[[Window alloc] init] autorelease] makeMainWindow];
[NSApp run];
}
It seems to work but if click 'Cancel' on the dialog , xcode gives me the following warning:
CLIENT ERROR: TUINSRemoteViewController does not override -viewServiceDidTerminateWithError: and thus cannot react to catastrophic errors beyond logging them
So i'm obviously not doing this in the correct way, how can I fix this?
Also, any feedback on this code as a whole is highly appreciated.
So I wanted to get my hands dirty with objective-c so I decided to create a project to list all outbound traffic, after digging a little I found that I could use the Network Extension API. I created a simple command line project with xcode and tried to load this extension but for some reason I can't get it to work.
I don't have a developer license yet and I'm not sure if it has anything to do with the problem I'm facing.
This is just some test code so there are 2 free functions, one for loading the system extension and another for checking its status:
// activates the extension?
BOOL toggleNetworkExtension(NSUInteger action)
{
BOOL toggled = NO;
__block BOOL wasError = NO;
__block NEFilterProviderConfiguration* config = nil;
dispatch_semaphore_t semaphore = 0;
semaphore = dispatch_semaphore_create(0);
NSLog(@"toggling the network extension");
[NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if(nil != error)
{
wasError = YES;
NSLog(@"loadFromPreferencesWithCompletionHandler error");
}
dispatch_semaphore_signal(semaphore);
}];
NSLog(@"waiting for the network extension configuration...");
if(YES == wasError) goto fail;
NSLog(@"loaded current filter configuration for the network extension");
if(1 == action)
{
NSLog(@"activating network extension...") ;
if(nil == NEFilterManager.sharedManager.providerConfiguration)
{
config = [[NEFilterProviderConfiguration alloc] init];
config.filterPackets = NO;
config.filterSockets = YES;
NEFilterManager.sharedManager.providerConfiguration = config;
}
NEFilterManager.sharedManager.enabled = YES;
}
else
{
NSLog(@"deactivating the network extension...");
NEFilterManager.sharedManager.enabled = NO;
}
{ [NEFilterManager.sharedManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if(nil != error)
{
wasError = YES;
NSLog(@"saveToPreferencesWithCompletionHandler error!");
}
dispatch_semaphore_signal(semaphore);
}]; }
NSLog(@"waiting for network extension configuration to save...");
if(YES == wasError) goto fail;
NSLog(@"saved current filter configuration for the network extension");
toggled = YES;
fail:
return toggled;
}
Then there's this function to check if the extension is enabled which for some reason always returns false.
BOOL isNetworkExtensionEnabled(void)
{
__block BOOL isEnabled = NO;
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) {
if (error != nil)
{
NSLog(@"Error with loadFromPreferencesWithCompletionHandler");
}
else
{
isEnabled = NEFilterManager.sharedManager.enabled;
}
dispatch_semaphore_signal(semaphore);
}];
return isEnabled;
}
Is something wrong is this code or is this related to entitlements or the developer license?
As a side note I have already disabled SIP not sure if it matters in this case.
Thanks in advance.
Topic:
App & System Services
SubTopic:
Networking
Tags:
Xcode
System Extensions
Objective-C
Network Extension
Hi Team,
I am using NSDateFormatter to print date and time in my logger class.
// Get current date and time
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *dateTimeString = [dateFormatter stringFromDate:[NSDate date]];
I am using the NSDateFormatter as shown in the above snippet, but I am seeing random crashes with the below stack trace. This crash is random and can't be reproduced consistently.
0 libobjc.A.dylib 0x7ff8051a021d objc_msgSend + 29
1 CoreFoundation 0x7ff8056609ef __CFDateFormatterSetSymbolsArray + 59
2 CoreFoundation 0x7ff80564db87 __ApplyUDateFormatSymbol + 324
3 CoreFoundation 0x7ff80564c854 __ResetUDateFormat + 3064
4 CoreFoundation 0x7ff80564bc30 __CreateCFDateFormatter + 320
5 Foundation 0x7ff8064c2ae3 -[NSDateFormatter _regenerateFormatter] + 323
6 Foundation 0x7ff8064c2858 -[NSDateFormatter stringForObjectValue:] + 297
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000018
Exception Codes: 0x0000000000000001, 0x0000000000000018
Termination Reason: Namespace SIGNAL, Code 11 Segmentation fault: 11
Terminating Process: exc handler [5372]
Can someone please suggest if there is something wrong in the way NSDateFormatter being used?
I checked the documentation and found nothing that can be causing this issue.
Thanks and Regards
I am developing an iPhone app related to finance and currently I am using isCaptured value to prevent screen recording by checking the isCaptured value and if it is true then I blur the video recording.
It was working fine while using UIScreen.main.isCaptured till iOS 17 . But for iOS 18 it became deprecated and it is not working any more. Below is the obj-c code block.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions
{
if (@available(iOS 11.0, *)) {
BOOL isCaptured = [[UIScreen mainScreen] isCaptured];
if(isCaptured){
// Do the action for hiding the screen recording
}
} else{
// Fallback on earlier versions
}
return YES;
}
The replacement sceneCaptureState is working only for a scene-based app which uses UISceneDelegate lifecycle but it's not working for the old structure so now i have that problem, my iPhone app is very big and does not support scenes at all since we are following UIAppDelegate life cycle for years, what shall I do to prevent screen recording from iOS 18 onwards ?
Note: My iPhone app does not support any scene configuration
Please help me in this.
Regards,
Carol
We have an app that captures images and videos and we share them to a server. Now at initial state the app works fine, but as we start using the app, the memory grows and my app crashes finally. Kindly help in identifying how to rectify and remove the resident memory and dirty memory.
When I trying to set share record I get:
NSOperationQueue * quwuw = [[NSOperationQueue alloc] init];
[quwuw setMaxConcurrentOperationCount:1];
[self createOrFetchZone:^(CKRecordZone *rzone, NSError *error) {
CKRecordID *recordID = [[CKRecordID alloc] initWithRecordName:recordId zoneID:custZone.zoneID];
[[self privateCloudDatabase] fetchRecordWithID:recordID completionHandler:^(CKRecord *record, NSError *error) {
if (error) {
dispatch_async(dispatch_get_main_queue(), ^{
prephandler(nil, nil,error);
});
return;
}
CKShare * share = [[CKShare alloc] initWithRootRecord:record];
share[CKShareTitleKey] = @"Some title";
[share setPublicPermission:CKShareParticipantPermissionReadWrite];
CKModifyRecordsOperation * op = [[CKModifyRecordsOperation alloc] initWithRecordsToSave:@[share, record] recordIDsToDelete:nil];
[op setModifyRecordsCompletionBlock:^(NSArray<CKRecord *> * _Nullable savedRecords, NSArray<CKRecordID *> * _Nullable deletedRecordIDs, NSError * _Nullable operationError) {
if (operationError == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
prephandler(share, [CKContainer defaultContainer],operationError);
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
prephandler(share, [CKContainer defaultContainer],operationError);
});
}
}];
[op setDatabase:[self privateCloudDatabase]];
[quwuw addOperation:op];
}];
}];
I get error:
Invalid Arguments" (12/2006); server message = "Chaining supported for hierarchical sharing only"
Any advices for this?
hi all,
i wrote my tool app using ObjC++, find some problems while messing with "locale". here's the problems:
I invoke a C++ function,
std::string ws2s(const std::wstring& ws)
{
if (ws.empty())
return "";
NSLog(@"%s %s", setlocale(LC_ALL, NULL), std::locale().name().c_str());
...
output is "C C", and i try to set locale to "zh_CN.UTF8", but it's still "C".
another is an Objc Class Method
+ (NSString*)getNSStrFromWCharStr:(const wchar_t*)wcstr {
if (wcstr == NULL) return nil;
char *curLocale = setlocale(LC_ALL, NULL);
...
this time, curLocale is the same as system default ——"zh_CN.UTF8"
I try to set locale in main function, first one succeed, second made process crash.
setlocale(LC_ALL, "zh_CN.UTF-8");
std::locale::global(std::locale("zh_CN.UTF8"));
crash info:libc++abi: terminating due to uncaught exception of type std::runtime_error: collate_byname::collate_byname failed to construct for zh_CN.UTF8
after all this, it's OK to handle CN character with C and objc, but it's not OK with C++. and I'm confused, I don't know much about 'locale'. I thought it was a per-process setting, now it seems to be a per-language setting...
OS version: macOS 14.4, system default locale is "zh_CN.UTF8".
Platform and Version
iOS
Development environment: Xcode 16.0 beta 5 (16A5221g), macOS 14.6.1 (23G93)
Run-time configuration: iOS 18.0 beta 5 (22A5326g)
Description of Problem
Starting with iOS 18 SDK, test bundles containing a +load method that accesses UIScreen.mainScreen result in deadlock during test bundle injection.
Also filed as FB14703057
I'm looking for clarity on whether this behavior is considered a bug in iOS or whether we will need to change the implementation of our app.
Steps to Reproduce
Create a new iOS app project using Objective-C and including unit tests
Add the following code snippet to any .m file in the test target:
@interface Foo: NSObject
@end
@implementation Foo
+ (void)load {
UIScreen * const mainScreen = UIScreen.mainScreen;
NSLog(@"%@", mainScreen);
}
@end
Run the tests
Expected Behavior
As with iOS 17 & Xcode 15, the tests run to completion.
Actual Behavior
With iOS 18 & Xcode 16, deadlock during test bundle injection.
stack_trace.txt
I want to implement a stack that works quite like a circular buffer.
void** pp = malloc(sizeof(id) * 100);
pp[index] = someObject;
// later on somewhere:
MyObject* myObj = (MyObject*)pp[index];
Is this correct? Does this approach work with ARC?
I have apps that send requests for route between 2 locations and search, filter then display facilities near the route. The apps first send a request for the route on a background thread, then based on route, search for facilities near certain locations on or near the route. There maybe multiple searches on the same route, each on a different location. Suitable results then are displayed on the map. Apps also do live updates.
However, since I have switched to using NSURLSession to search for the route on a background thread, not all suitable results/pin are displayed. Certain pins only show up upon the next didUpdateToLocation call.
So my question is, what is the best practice to sync the results on the UI? Why do only some of the results show up on the UI, and others don't.
We're developing a new version of the app written entirely in SwiftUI, while the previous version was written in Objective-C. However, my company needs to ensure that the app can run on iOS 12. Is there any way to make SwiftUI compatible with iOS 12?
I think I found a bug in the Objective-C++ compiler, linker, or runtime. Here’s the scenario:
We have a macOS app written in Swift.
To control hardware from a 3rd party manufacturer, we use a couple SDKs provided by the manufacturer.
The SDKs use dynamically loaded libraries and the interface is defined in C++ headers.
To bridge between our Swift code and the C++ APIs we have a private Cocoapod that wraps the 3rd party interface with Objective-C++ classes.
The two SDKs each provide an interface for discovering attached devices using a callback class that the programmer provides. By accident we named both callback implementations DiscoveryCallback, but this was not a compiler error because neither class was publicly declared, and each was defined in the .mm file where it was used.
However, the problem we’re seeing is this:
We want to discover Videohub devices, so we register a new instance of DiscoveryCallback (defined in the same .mm file as this code) with the Videohub SDK.
A Videohub device is connected and the SDK calls a method on our callback.
Surprise! The callback we registered in step 1 was actually the one intended for Decklink devices, defined in a completely different .mm file.
This violates all sorts of assumptions and our app quickly crashes.
The funny thing is, the two implementations of DiscoveryCallback have completely different method names. The Videohub SDK is supposed to be calling NewVideohubDevice, yet somehow it successfully calls DeckLinkDeviceArrived on an instance of a class it shouldn’t even know about.
So the compiler has checked that our intended DiscoveryCallback matches the protocol that the SDK expects, but at runtime the compiled code instantiates a completely different implementation of DiscoveryCallback and somehow doesn’t immediately fail; we still call a method on it that doesn’t even share a name with the intended target. I imagine at this point the method names are long forgotten and are just pointers in a table.
I don’t know if this is a bug in the compiler, the Objective-C++ runtime, or if this is just “working as designed” undefined behavior that I should have avoided by not giving two private classes the same name. I know it’s possible to use a private API simply by redeclaring it in my own code, and this seems related to that, but I feel like the compiler or linker should have warned me that I had two implementations of the same class, or if that is not an error, then the runtime should have instantiated the class that was privately defined in the same source file where it was used.
Obviously I can’t share our entire project; I’d like to provide some sample code that replicates the issue, but I don’t have time to do that right now. I’m posting this to see if other developers have had a similar experience.