When user enters in a textfield, is the input of textfield gets stored in a String ?
If yes, then String in swift being immutable, as user keeps on typing does new memory for storing that text gets allocated with each key stroke ?
And when we read users input by using delegate method textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) from textfield.text, we get users input in a String. Is it same storage as used by textfield for storing the user input on key stroke or is it some other storage with copy of the user's input in it?
Or is UItextfield using a diffrent data structure (buffer) for storing the user input and when we do textfield.text, it gives a copy of data stored in original buffer?
Post
Replies
Boosts
Views
Activity
When i create a intance of swift String :
Let str = String ("Hello")
As swift String are immutable, and when we mutate the value of these like:
str = "Hello world ......." // 200 characters
Swift should internally allocate new memory and copy the content to that buffer for update .
But when i checked the addresses of original and modified str, both are same?
Can you help me understand how this allocation and mutation working internally in swift String?
In below Swift code , is there any possiblities of failure of Unmanaged.passRetain and Unmanaged.takeRetain calls ?
// can below call fail (constructor returns nil due to OS or language error) and do i need to do explicit error handling here?
let str = TWSwiftString(pnew)
// Increasing RC by 1
// can below call fail (assuming str is valid) and do i need to do explicit error handling for the same ?
let ptr:UnsafeMutableRawPointer? = Unmanaged.passRetained(str).toOpaque()
// decrease RC by 1
// can below call fail (assuming ptr is valid) ? and do i need to do explicit error handling
Unmanaged<TWSwiftString>.fromOpaque(pStringptr).release()
In my project, i have a Swift class with a class level property of type string. Like this :
class TWSwiftString {
var pString:String!
init(_ pString: String) {
self.pString = pString
}
}
I am creating intance of this class and then creating a opaque pointer to this intance. Like this :
let str = TWSwiftString("World")
// Increasing RC by 1
strptr = Unmanaged.passRetained(str).toOpaque()
Now using this opaque pointer i want to modify the value of pString by directly operating on memory. Like this:
withUnsafeMutablePointer(to: &strptr.pString) { strPointer in
strPointer.pointee = "World"
}
Although i am able to modify pString like this and print. Lets assume i have a approach to make sure memory remains valid when it is operated on and freeing of memory is also handled somehow .
Will this approach work if i have 100s of intance of this string which are being operated in this manner ? What if the size of new value is greater than existing string value ? For this i am thinking of chunk of memory initially and then keep on increasing size of it as bigger string then this chunk comes. Does this approach seems feasible ? Any other problems i can encounter by using this approach ?
Chatgpt gave this answer :
To directly update the memory of a Swift class’s property, particularly to alter a String property, is generally discouraged due to Swift's memory safety model. However, if we want to access and modify a class property directly, the best practice is to use a property accessor, as manually altering memory could lead to undefined behavior or even crashes. Why Direct Memory Manipulation Is Risky When you attempt to manipulate memory directly, especially with Swift’s memory model, you might alter not only the value but also the memory layout of Swift’s String type, which could break things internally. The Swift compiler may store String differently based on the internal structure, so even if we manage to locate the correct memory address, directly modifying it is unreliable.
do you have any opinion around chatgpt resoponse ?
For calling swift api of a class to cpp , we need to include SwiftInterfaceGeneratedHeader to cpp file and then we can access swift class api in cpp . Signature of swift class with public apis will be added to the SwiftInterfaceGeneratedHeader.
We find an odd behaviour here . Signature of classes will be added to SwiftInterfaceGeneratedHeader in alphabetical order (swift class name alphabetically lower will be added first to generated header).
If we have a swift class which is referenced by another swift class Api , then referenced class's name should be alphabetically lower that referee class , otherwise we will get a build error :- "Unknown class name".
public class A {
public func funca () {
print ("class A")
}
}
public class B {
public func funcb () {
print ("class B")
}
public func funcb2 (pA:A) {
pA.funca()
}
public func funcb3 (pC:C) {
pC.funcc()
}
}
public class C {
public func funcc () {
print ("class C")
}
}
Cpp class where we include bridging header after turning on swift cpp interop :
class Test1 {
public:
static void testfunc ();
};
#include "Test1.hpp"
#include "cppswiftinterop-Swift.h"
void
Test1::testfunc()
{
}
Here , we have three swift classes , Class A,B,C. And since we are including SwiftInterfaceGeneratedHeader in cpp , signature of these class will be added to the generated header . In this project , we are referencing Class A and Class C from Class B .
And since A is alphabetically lower that B , it works fine (because signature of A in Generated header will be added before it is referenced by B). But since C is alphabetically above than B , it will through build error (Unknown type name 'C') , because Signature of C in Generated header will be added after it is referenced by class B).
If i rename Class C to Class AA then , it works fine.
Is this a bug in swift cpp interop?
For printing from worker thread to a UIPrinter(whose url i have saved ) i am doing this and able to print :
func PrintPdfDocument (pDocument:Data)
{
// Create a print interaction controller
let printController = UIPrintInteractionController.shared
// Set the printing options
let printInfo = UIPrintInfo(dictionary:nil)
printInfo.jobName = "Print Job "
printController.printInfo = printInfo
printController.showsPageRange = true
// Set the PDF document to be printed
printController.printingItems = pDocument
printController.print(to: defaulttprinter, completionHandler: { (controller, completed, error) in
if completed {
print("Printing successful!")
} else {
if let error = error {
print("Printing failed with error: \(error.localizedDescription)")
} else {
print("Printing was canceled.")
}
}
})
}
When i call PrintPdfDocument (pDocument:Data) function , more than once with diffrent data shown below :
DispatchQueue.global().async {
PrintPdfDocument (pDocument:data1)
}
DispatchQueue.global().async {
PrintPdfDocument (pDocument:data2)
}
DispatchQueue.global().async {
PrintPdfDocument (pDocument:data3)
}
Printer is printing only one document(data1) .
For other call is not executing printController.print (to....) function inside PrintPdfDocument.
I have a tvOS project contains an App target and 3 static libraries:
EntryPoint – Static library that contains main , AppDelegate and SceneDelegate
Experience – Static library containing my UI elements
AppTarget – executable built using above two libraries
I have a class "SelectionTable" which subclasses UITableView in Experience target :
import UIKit
class SelectionTable : UITableView
{
private var vDataSrc:[String]!
func SetDataSrc (_ pDataSrc:[String])
{
self.vDataSrc = pDataSrc
}
func UpdateDataSrc (_ pStringList:[String])
{
self.vDataSrc += pStringList
}
func GetDataSrc () -> [String]
{
return self.vDataSrc
}
}
I am not using this class anywhere and still i am getting these errors when i build my AppTarget:
Cannot find interface declaration for 'UITableView', superclass of 'SelectionTable'
Expected a type
These above error are coming in generated header file "Experience-Swift.h". This file is auto-generated by compiler. I am not using @objc anywhere in the code, But still the Target-Swift.h file has the below lines:
SWIFT_CLASS("_TtC10Experience22SelectionTable")
@interface SelectionTable : UITableView
- (nonnull instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style OBJC_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)coder OBJC_DESIGNATED_INITIALIZER;
@end
When i am marking above class as Private , this error goes away .
And also , if i am defining SelectionTable class in EntryPoint library , this error does not occur .
I am using similar model for an iOS project also and there i am not facing this issue.
I am using :-
Swift version : Swift 5.9.2
XCode version : 15.2
I want to use CUPS in iOS for printing and it is mentioned at many places that we can use cups for printing in ios .But when i import library cups/cups.h ,xcode is giving error "cups/cups.h not found".
code i am using in a objective c file :
import &lt;cups/cups.h&gt;
cups_dest_t *dest;
int num_options;
cups_option_t *options;
int job_id;
/* Print a single file */
job_id = cupsPrintFile(dest-&gt;name, "/usr/share/cups/data/testprint.ps",
"Test Print", num_options, options);
Do i need to intall some driver or any library to make it work ? or is it the case that CUPS is not available for iOS?
when i am adding new view to replace viewcontroller's view like this :
let viewcontroller: UIViewController!
let rootview:UIView!
viewcontroller = UIViewController ()
rootview = UIView (frame:viewcontroller.view.bounds)
viewcontroller.view = rootview
// Adding a button
let button = UIButton(type: .system)
button.setTitle("Tap Me", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.addTarget(self, action: #selector(buttonTapped), for:.allEvents)
viewcontroller.view.addSubview(button)
For ios(iPhone/ipad) , i am able to get button click event .
But in case of tvOS , i am not getting button click event.
But in case of tvOS if use the default view of viewcontroller like this , i am getting button click events and things works fine:
let viewcontroller: UIViewController!
viewcontroller = UIViewController ()
// Adding a button
let button = UIButton(type: .system)
button.setTitle("Tap Me", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
button.addTarget(self, action: #selector(buttonTapped), for:.allEvents)
viewcontroller.view.addSubview(button)
Is this some bug for tvOS or for tvOS this suppose to happen this way ?
I want to use uitableview in tvos to show list of string data but compiler is throughing following errors in generated header:
"No type or protocol named 'UITableViewDataSource'"
And "Attempting to use the forward class 'UITableView' as superclass of 'TWOSSelectionTableTVOS'"
Even though this code is working is ios .
My code structure is as follow :
SelectionTable.swift:
import UIKit
class TWOSSelectionTableTVOS : UITableView
{
private var vDataSrc:[String]!
func SetDataSrc (_ pDataSrc:[String])
{
self.vDataSrc = pDataSrc
}
func UpdateDataSrc (_ pStringList:[String])
{
self.vDataSrc += pStringList
}
func GetDataSrc () -> [String]
{
return self.vDataSrc
}
}
PaintUI.swift :
import UIKit
@objc
class PaintUI: NSObject,UITableViewDelegate, UITableViewDataSource {
static let uShared = PaintUI ()
@objc
static func updateUIMessage() {
DispatchQueue.main.async {
ExecuteInlineSelectionTable ()
}
}
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell (withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "hello"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewcontroller: TWIOSViewController!
viewcontroller = StaticContext.sViewController
}
public static func ExecuteInlineSelectionTable ()
{
let selectiontable:TWOSSelectionTableTVOS!
selectiontable = TWOSSelectionTableTVOS ()
selectiontable.register (UITableViewCell.self, forCellReuseIdentifier: "cell")
selectiontable.dataSource = uShared
selectiontable.delegate = uShared
selectiontable.isScrollEnabled = true
// TODO : will add selection table in view heriearchy but currently getting
// compilation error
}
}
And finally calling PaintUI.updateUIMessage () , it is throughing above errors for tvOS only but in case of ios code is working fine.
when i select target as "All builds" i am getting list of simulators .
but when i select target as "SCPNative" i am not getting list of simulators.
Deployment target is 7.0 whereas sdk is 10.2.
Is there any way to get list of system shortcuts set by user or reserved by os programatically?
In my application i want to override the default behavior of undo and redo .In ipad , when user presses cmd+c/v , want to trigger some other action instead of default copy/paste . And in case of ipad , i want to trigger diffrent action for three finger touch gesture . Is it possible to do that?
I want to attach a three pinch zoom to my UITableView .
When user uses three pinch zoom i want to show more details in uitableview where as in two pinch zoom i want normal zoom behavior . But when i am using UIPinchGesture it is only giving numberOfTouches as 2 even when i use three fingers .