Objective-C

RSS for tag

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

Posts under Objective-C tag

214 Posts
Sort by:
Post not yet marked as solved
0 Replies
249 Views
Is it possible that I bypass tableView.makeView so that I can create a NSTableCellView on the fly (based on some logics)? func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if NSTableColumn.identifier.rawValue == "labelColumn" { let myCellView = NSTableCellView() myCellView.textField.strinValue = "label text" return myCellView } else { let complexView = loadFromNib() // of NSTableCellView // populate complexView return complexView } }
Posted
by imneo.
Last updated
.
Post not yet marked as solved
2 Replies
324 Views
My macOS application utilizing NEDNSProxyProvider. i have a requirement to intercept only DNS requests of a certain query type, while others are expected to continue to their respective origin. For TCP there are two kinds of extensions NEAppProxyProvider and NETransparentProxyProvider. The latter is capable of returning NO from handleNewFlow causing the flow to proceed to communicate directly with the flow’s ultimate destination, instead of closing the flow. Is there a way to configure NEDNSProxyProvider to work in transparent mode for letting the flow to proceed to communicate directly? Current NEDNSProxyProvider limitation of dropping the connection when NO is returned requies me to open new socket and proxy the requests which causes noticable performance degradation under load.
Posted
by alzix.
Last updated
.
Post not yet marked as solved
0 Replies
275 Views
I have an older project with a mixed ObjC + Swift codebase. I'm in the process of converting everything to Swift in the hopes that Xcode will work better again when the Codebase is not mixed anymore. This is an example of the issues I'm currently facing: The class IVMapViewController is defined in ObjC and the property mapViewModel is declared in the ObjC Header fine. The ObjC Header file is included in the bridging header. I'm trying to access the property mapViewModel in an swift extension on the same class. I can actually compile & run the code just fine, but Xcode Autocompletion does not work, and Xcode generates "Phantom" errors in the Issue Navigator (those errors also stay there when a build completes successful) On the other hand, if I put an actual error in the code, compilation fails, but the actual error will NOT show up in the Issue Navigator. I'll have to dig through the build log to find the actual error. Am I doing anything wrong? Do I need to adjust some project setting?
Posted
by mexx.
Last updated
.
Post not yet marked as solved
1 Replies
229 Views
In objective-c, I created a category, like @interface NSArray <__covariant ObjectType> (ppEx) @end Look at this ObjectType, I wrote a method like - (NSArray *)pp_map:(id(^)(ObjectType element))block;which act like the map function in Swift. you can call it like NSArray <NSString *>*values = @[@"1", @"2", @"3", @"4"]; NSArray *valueMap = [values pp_map:^id _Nonnull(NSString * _Nonnull element) { return [NSString stringWithFormat:@"Hello %@", element]; }]; Now I need to add a property like mapBlock, I want to realize the same func; @property (nonatomic, copy) NSArray *(^mapBlock)(id(^paramBlock)(ObjectType element)); I did it. But when I call this method in Xcode, it can't complete automatically. values.mapBlock(^id _Nonnull(ObjectType _Nonnull element) { }) It's unable to recognize type NSString, and always show ObjectType which can cause error. I can manually change it to NSString, but it's too complicated. I think it's a problem of Xcode. Can anybody help me?
Posted Last updated
.
Post not yet marked as solved
0 Replies
359 Views
Hello. I have three questions about the Sensitive Content Analysis (SCA) framework: SCA seems to be asynchronous. Is there a limit to how much a single app can send through it at a time? For video analysis, can the video be broken into smaller chunks, and then all chunks be hit concurrently? Can a video stream be sampled as it's being streamed? e.g. Maybe it samples one frame every 3 seconds and scans those? Thanks.
Posted
by onehat.
Last updated
.
Post not yet marked as solved
2 Replies
339 Views
I have some Swift classes in my project that extend an Objective-C base class, which in turn extends NSObject. I did this years ago when Swift was new in order to take advantage of some Objective-C code that was difficult to rewrite in Swift. It's not a common situation but it has been working fine for a long time. One of these classes is used as the key to a Dictionary and thus needs to be Hashable. The way I did this was to implement an == function and override the 'hash' property. It is a very simple case where the identity of the object is based on a single integer: static func == (lhs: FishModel, rhs: FishModel) -> Bool { return lhs.fishId == rhs.fishId } override var hash: Int { return fishId } I believe that I initially tried to add "Hashable" to the class definition but was told it was redundant. I'm not sure why that is, but it worked fine without it. Today I took the latest Xcode update to 15.2, and now my project won't compile anymore. The compiler error says that my class "does not conform to protocol Hashable". Adding Hashable to the class definition did not fix it. There are also some unusual errors about missing files, such as abi.json, swiftdoc, swiftmodule, and swiftsourceinfo. Was this caused by the Xcode update? How do I fix it?
Posted Last updated
.
Post not yet marked as solved
0 Replies
319 Views
My application requires me to clear all the notifications from the notification centre after a certain time duration. I have tried using a combination of removeAllDeliveredNotifications & removeAllPendingNotificationRequests and they work fine up until OS 17. So then I tried using removeDeliveredNotificationsWithIdentifiers & removePendingNotificationRequestsWithIdentifiers to check if it works consistently for all OS, but they hasn't worked either. Is there any other way to clear the notifications consistently for all OS?
Posted
by jithinb1.
Last updated
.
Post marked as solved
2 Replies
323 Views
I have the following pseudo code: func load(at packageURL: URL) { let realPackageURL = packageURL.resolvingSymlinksInPath() guard let it = fileMan.enumerator(at: realPackageURL) for case let fileURL as URL in it { print(fileURL) // Get filename relative to package root directory let relativeFileName = String(filePath.suffix(filePath.count - packagePath.count)) } } When called with "file:///tmp/some.app", the enumerated fileURL is actually file:///private/tmp/GIMP.app/Contents/ packageURL.resolvingSymlinksInPath() actually does nothing, I assume /tmp is a hard link. This makes it impossible to get a correct relative path. Is there any remedy for this?
Posted
by imneo.
Last updated
.
Post marked as solved
4 Replies
741 Views
I'm encountering an issue with the latest versions of Xcode (15.1 and 15.2) while programming in Objective-C. When I try to create a category or an extension for a class, the process does not succeed and there is no response, with the category file not being created. This problem was not present in Xcode 15.0.1. My development environment is macOS Ventura 13.6.1. This bug is affecting my development work significantly. Could you please investigate this issue and provide a solution? Thank you for your assistance. 我在使用最新版本的Xcode(15.1和15.2)进行Objective-C编程时遇到了一个问题。当我尝试为一个类创建分类或扩展时,过程并不成功,没有任何反应,且分类文件没有被创建。在之前的版本Xcode 15.0.1中并没有这个问题。我的开发环境是 macOS Ventura 13.6.1。这个bug严重影响了我的开发工作。您能否调查此问题并提供解决方案?感谢您的帮助。
Posted
by YuanHong.
Last updated
.
Post not yet marked as solved
3 Replies
401 Views
I have this Objective-C code that works well if placed inside viewDidAppear method - rotates view into the Portrait orientation; UIWindowScene *windowScene = self.view.window.windowScene; if (!windowScene) { return; } UIWindowSceneGeometryPreferences *preferences = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:UIInterfaceOrientationMaskPortrait]; [windowScene requestGeometryUpdateWithPreferences:preferences errorHandler:^(NSError * _Nonnull error) { // Handle error here }]; Now I need to do that same rotation after user pressed Read button but before the selected document is loaded in another view. The problem - I can't figure out how to force view update after the code is executed. I see initial view rotated only after exiting that selected document, but I need it rotated before entering it. Thank you
Posted Last updated
.
Post marked as solved
5 Replies
377 Views
I have a need to read first half and second half of a file concurrently. Is there any best practices for this scenario? BTW, I did research on DispatchIO but it turned out DispatchIO is all about asynchronous operations on a single file handle; it cannot perform parallel reading. // naive approach Task { fileHandle.read(into:buffer) } Task { // seek to file size / 2 fileHandle.read(into:buffer) }
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
334 Views
I need to instantly and without rotation animation change the screen orientation (and accordingly the size of the frame self.view in the UIViewController). If I do it like this in UIViewController: - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id&lt;UIViewControllerTransitionCoordinator&gt;)coordinator { [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator]; [CATransaction begin]; [CATransaction setDisableActions:YES]; [coordinator animateAlongsideTransition:^(id&lt;UIViewControllerTransitionCoordinatorContext&gt; context) { [self.view setFrame:CGRectMake(0, 0, size.width, size.height)]; } completion:^(id&lt;UIViewControllerTransitionCoordinatorContext&gt; context) { [CATransaction commit]; }]; } Then, at the moment the screen orientation changes to, I see a flickering of view. How can I do what is necessary?
Posted
by kfvsc.
Last updated
.
Post not yet marked as solved
2 Replies
497 Views
Im getting a duplicate symbols error when I build my Xcode project and Xcode doesn't specify what or where in my code is there a duplicate: "1 duplicate symbols" "Showing Recent Issues Linker command failed with exit code 1 (use -v to see invocation) " #include <stdio.h> #include <IOKit/IOKitLib.h> typedef struct { uint32_t datasize; uint32_t datatype; uint8_t data[32]; } SMCVal_t; 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 *key, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)key; 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' float temp = *(float *)val -> data; return temp; } } } return 0.0; } double getTemperature(char *key) { SMCVal_t val; kern_return_t result; result = readSMC(key, &val); if(result == kIOReturnSuccess) { if (val.datasize > 0) { printf("val.datasize: %u\n", val.datasize); if (val.datatype != 0) { double temperature = (double)val.data[0]; return temperature; } } } return 0.0; } double convertToFahrenheit(double Fahrenheit) { return (Fahrenheit * (9.0 / 5.0)) + 32.0; } int main(void) { kern_return_t result; result = openSMC(); if(result == kIOReturnSuccess) { double temp = getTemperature("TC0P"); double temperatureInFahrenheit = convertToFahrenheit(temp); printf("temp: %.2f\n", temperatureInFahrenheit); result = closeSMC(); } return 0; }
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
1 Replies
443 Views
I tried to archive a NSDictionary with a NSColor : data = [NSKeyedArchiver archivedDataWithRootObject: &lt;vrRoot&gt; requiringSecureCoding:YES error:&amp;error]; and I get this error : Printing description of error: Error Domain=NSCocoaErrorDomain Code=4864 "value for key 'NS.objects' was of unexpected class 'NSColor' (0x7ff8465d0d88) [/System/Library/Frameworks/AppKit.framework]. Allowed classes are: {( "'NSMutableDictionary' (0x7ff8465f9b48) [/System/Library/Frameworks/CoreFoundation.framework]" )}" UserInfo={NSDebugDescription=value for key 'NS.objects' was of unexpected class 'NSColor' (0x7ff8465d0d88) [/System/Library/Frameworks/AppKit.framework]. Allowed classes are: {( "'NSMutableDictionary' (0x7ff8465f9b48) [/System/Library/Frameworks/CoreFoundation.framework]" )}} Then I transferred NSColor to NSArray - but the error was the same. I want data save in Core Data, please help me ♡.
Posted Last updated
.
Post marked as solved
4 Replies
364 Views
I have a single-line label whose purpose is display file path, possibly very long. Is there any way to shorten/compact the path string (with ellipse ...) so that the label still displays full path even it's too long? Like below: /some/very/long/path/to/some/filename.txt to /some/.../filename.txt
Posted
by imneo.
Last updated
.
Post not yet marked as solved
0 Replies
483 Views
I have this code to create an IOSurface from a bitmap image: auto src = loadSource32f(); // rgba 32-bit float image const auto desc = src-&gt;getDescriptor(); // metadata for that image auto pixelFmt = CGMTLBufferManager::getCVPixelFormat( desc.channelBitDepth, desc.channelOrder ); // returns proper `RGfA` int width = static_cast&lt;int&gt;( desc.width ); int height = static_cast&lt;int&gt;( desc.height ); int trowbytes = static_cast&lt;int&gt;( desc.trueRowbytes() ); // returns proper rowbytes value CFMutableDictionaryRef properties = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &amp;kCFTypeDictionaryKeyCallBacks, &amp;kCFTypeDictionaryValueCallBacks ); CFDictionarySetValue( properties, kIOSurfaceWidth, CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &amp;width ) ); CFDictionarySetValue( properties, kIOSurfaceHeight, CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &amp;height ) ); CFDictionarySetValue( properties, kIOSurfacePixelFormat, CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &amp;pixelFmt ) ); CFDictionarySetValue( properties, kIOSurfaceBytesPerRow, CFNumberCreate( kCFAllocatorDefault, kCFNumberIntType, &amp;trowbytes ) ); NSDictionary *nsprops = ( __bridge NSDictionary * )properties; IOSurface *oSurface = [[IOSurface alloc] initWithProperties:nsprops]; CFRelease( properties ); ASSERT_TRUE( oSurface ); auto ioSurface = (IOSurfaceRef) oSurface; I tested that the pixels are properly written into the iosurface: // copy data to surface memcpy([oSurface baseAddress], src-&gt;getRawPtr(), src-&gt;getSizeInBytes()); auto surfPtr = (uint8_t*)[oSurface baseAddress]; // extract raw surface data and write it into a file saveOutputRaw(desc, surfPtr, getFileName("IOSurfaceTestSurfaceRaw")); And I see this: Now I want to create a MTLTexture based on the iosurface: // create texture auto fmt = IOSurfaceGetPixelFormat( ioSurface ); auto w = IOSurfaceGetWidth( ioSurface ); auto h = IOSurfaceGetHeight( ioSurface ); auto rowbytes = IOSurfaceGetBytesPerRow( ioSurface ); MTLTextureDescriptor *textureDescriptor = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:CGMTLBufferManager::getMTLPixelFormat( fmt ) width:w height:h mipmapped:NO]; textureDescriptor.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite; textureDescriptor.storageMode = MTLStorageModeShared; auto device = MTLCreateSystemDefaultDevice(); id&lt;MTLTexture&gt; surfaceTex = [device newTextureWithDescriptor:textureDescriptor iosurface:ioSurface plane:0]; And now I want to test this: auto region = MTLRegionMake2D(0, 0, w, h); auto bufSize = [oSurface allocationSize]; // get texture bytes auto outBuf2 = std::vector&lt;uint8_t&gt;(bufSize); [surfaceTex getBytes:outBuf2.data() bytesPerRow:rowbytes fromRegion:region mipmapLevel:0]; // save to file saveOutputRaw(desc, outBuf2.data(), getFileName("IOSurfaceTestCreateTex")); // get bytes saveOutputRaw(desc, surfPtr, getFileName("IOSurfaceTestCreateRaw")); And I get this result: I also tried replaceRegion and blitEncoder copyFromTexture: toTexture: as well as managed texture with syncing, but the result is always the same - only the first 22 pixels get filled and the rest is transparent. I have no idea what I'm missing. Please help.
Posted
by BartW.
Last updated
.
Post not yet marked as solved
1 Replies
558 Views
Date/Time: 2023-12-22 10:15:42.0985 +0800 Launch Time: 2023-12-22 10:12:52.8757 +0800 OS Version: iPhone OS 17.1.2 (21B101) Release Type: User Baseband Version: 4.06.02 Report Version: 104 Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 3131951633 &amp;lt;RBSTerminateContext| domain:10 code:0xBAADCA11 explanation: reportType:CrashLog maxTerminationResistance:Interactive&amp;gt; Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1e6bfc1d8 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1e6bfbf70 mach_msg2_internal + 79 2 libsystem_kernel.dylib 0x1e6bfbe88 mach_msg_overwrite + 435 3 libsystem_kernel.dylib 0x1e6bfbcc8 mach_msg + 23 4 CoreFoundation 0x19f725d0c __CFRunLoopServiceMachPort + 159 5 CoreFoundation 0x19f723c04 __CFRunLoopRun + 1207 6 CoreFoundation 0x19f723668 CFRunLoopRunSpecific + 607 7 GraphicsServices 0x1e2aee5ec GSEventRunModal + 163 8 UIKitCore 0x1a1b402b4 -[UIApplication _run] + 887 9 UIKitCore 0x1a1b3f8f0 UIApplicationMain + 339 10 iCSee 0x103921380 main + 115 (main.m:17) 11 dyld 0x1c2176dcc start + 2239
Posted
by JF001.
Last updated
.
Post not yet marked as solved
2 Replies
476 Views
I have a C file for accessing the apple smc and I have the corresponding header file with my declarations in it but when I build my Xcode project I get the error: "ld: Undefined symbols: _getTemperature, referenced from: _main in getsmc.o clang: error: linker comm" #include &lt;stdio.h&gt; #include &lt;IOKit/IOKitLib.h&gt; typedef struct { uint32_t datasize; uint32_t datatype; uint8_t data[32]; } SMCVal_t; 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"), &amp;iterator); if(service == 0) { printf("error: could not match dictionary"); return 0; } result = IOServiceOpen(service, mach_task_self(), 0, &amp;conn); IOObjectRelease(service); return 0; } kern_return_t closeSMC(void) { return IOServiceClose(conn); } double getTemperature(char *key); kern_return_t readSMC(char *key, SMCVal_t *val) { kern_return_t result; uint32_t keyCode = *(uint32_t *)key; SMCVal_t inputStruct; SMCVal_t outputStruct; inputStruct.datasize = sizeof(SMCVal_t); inputStruct.datatype = 'I' &lt;&lt; 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, &amp;inputStruct, sizeof(SMCVal_t), &amp;outputStruct, (size_t*)&amp;inputStruct.datasize); if (result == kIOReturnSuccess) { if (val -&gt; datasize &gt; 0) { if (val -&gt; datatype == ('f' &lt;&lt; 24 | 'l' &lt;&lt; 16 | 't' &lt;&lt; 8 )) { float temp = *(float *)val -&gt; data; return temp; } } } return 0.0; } int main(void) { kern_return_t result; result = openSMC(); if(result == kIOReturnSuccess) { double temp = getTemperature("TC0P"); printf("temp: %.2f\n", temp); result = closeSMC(); } return 0; }
Posted
by Aor1105.
Last updated
.
Post not yet marked as solved
3 Replies
390 Views
I am working on the project in which we are migrating from iOS project to framework. I am facing issue with Objective-C and swift interoperability. I have one Swift class let suppose profile, it has been exposed to objective c import Foundation @objc public class Profile: NSObject { @objc public var name : String? @objc public func getName() -> String{ return "XYZ" } } When I am importing “ProductName-Swift.h” it is showing me error in generated header for the module map like “@import ModuleMapPrivate not found” I wanted to know is there any way in which I can import “Profile-Swift.h” instead of “ProductName-Swift.h” ?
Posted
by shikha25.
Last updated
.