How to Access Text in a Text Field [duplicate] - swift

I'm trying to set the text in an NSTextField, but the -setStringValue: and -setTitleWithMnemonic: methods are not working. Any ideas?

setStringValue: is the way to do it. You should make sure your outlet is being set properly. (In the debugger, make sure your textfield variable is not null.)

Just do something like this:
myLabel.stringValue = #"My Cool Text";

Just myLabel.stringValue = "MY TEXT" works here, using Swift and Xcode 6.

Swift 4
self.yourTextField.stringValue = "Your_Value"
Note: Fetching value from self.yourTextField.stringValue at that will get warning message i.e.
To avoid this kind of warning you can use like this (suggested way)
DispatchQueue.main.async {
your code ...
}
OR also refer to this.

If the value you're trying to set happens to be an integer rather than a string, you don't need to convert the integer value to a string manually; you can just call:
myLabel.integerValue = i;
The integerValue property is defined on NSTextField's parent class, NSControl. See that linked documentation page for a full list of methods it supports.

ObjectiveC:
[label setStringValue: #"I am a label"];
original code I use in my code to display application version is:
[lblVersion setStringValue:[NSString stringWithFormat:#"v%#", [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleShortVersionString"]]];

just do this
[textField setString:#"random"];

Related

When to use . parameter and when to use [ ] to call a function in IOS

In iOS I have some confusion when calling a function.
-(void) function:(NSString*) str
{
selectedstring = str;
}
When calling the function.
When should I call like:
self.function = #"My name";
and
[self function:#"My name"]
What is the difference between (.) parameter and [ ]
in iOS function calling?
myVar = self.property is equivalent to myVar = [self property]
self.property = anotherVar is equivalent to [self setProperty:anotherVar]
Which you use is a matter of style.
Some people will tell you that the dot syntax should only be used for things that are actually defined as properties (with #property). I disagree with this. My opinion is that the dot syntax should be used whenever you're calling something that gets or sets a value, with minimal other side effects. Whether you have written the method yourself or synthesized a property to auto-generate it is not important: the important thing is whether it is related to getting and setting a value.
So myArray.count is fine, despite it not being a #property in the header file. But myURLConnection.start is not, since that doesn't return a value and is related to performing an action.
People do disagree with this. Some people don't like using dot syntax at all, since it could be confused with accessing the members of a struct (which also use .). Others are happy to use dot syntax for #propertys, but not for other methods.

How to display the contents of a variable in a UITextField

I passed a variable from first.m to seViewController.m. I'm able to print that variable using NSLog(#variable) but I'm unable to use textField.text=variable. How to print that variable in a textbox?
-(void)insert:variable
{
NSLog(#"%#",variable);
textfield.text=variable;
}
In my text box value is not coming...
You can try
textfield.text=[variable description]; // or -localizedDescription
That's what is used when you print your object using NSLog.
However it may be more appropriate to get some textual attributes from your object and then assign them to textField. That will depend, of course, of what type your variable is, what info it contains and how you want to print it...
Try This code:
-(void)insert:(NSString*) variable
{
NSLog(#"%#",variable);
textfield.text=[NSString stringWithFormat:#"%#",variable];
}
Try with below
-(void)insert:(NSString*) variable
{
NSLog(#"%#",variable);
textfield.text=variable;
}
You don't indicate variable's type in your code snippet (is that valid Objective-C syntax?). If it's an NSString, your code should work as is. If it's any object type (including NSString), you can use the description method to get a descriptive string.
If it's a C primitive (int, float, etc.) you will have to create an NSString (possibly using [NSString stringWithFormat].

Objective-c pointers and NSString

If I have this code, why doesn't the textview's text update? As far as I knew a * meant a pointer, and I haven't done a copy.
NSString *searchText = myTextView.text;
searchText = [searchText stringByReplacingOccurrencesOfString:#" " withString:#";"];
So why isn't myTextView's text changed as if I did:
myTextView.text = [searchText stringByReplacingOccurrencesOfString:#" " withString:#";"];
And how would I write the code, so that the first code example works as I intend?
The method stringByReplacing... Doesn't change the string, it returns a new string object (autoreleased, according to the naming conventions). So after the 2nd line of code, searchText points to a totally differen NSString object.
Besides, NSString objects cannot be changed, for that there's NSMutableString
If you expect to modify myTextView.text, you have to write it like your second example, and assign a new value to the property you're trying to modify. Assigning a new value to some other variable or property won't do the job - "spooky action at a distance" may work when we eventually have quantum computing, but we're not there yet. :-)
To expand a bit: Yes, searchText is a pointer. But so is myTextView.text, and when you do "searchText = myTextView.text", you're not creating any sort of lasting relationship between the two - all you're doing is making searchText point to the same target as myTextView.text. Changing either one of them after that point will have no effect on the other. So, when you assign the result of stringByReplacing... to searchText, you're making it and only it point to a different target.
Your second example invokes the setter of the "text" property.
Your first example takes the pointer of the string, and then changes the pointer within the same scope. Hence, "text" is not changed.
BTW: Depending on how your property is defined, the setter you use will either copy, retain or assign the value you give the setter. So if you use the following:
#property(copy) NSString* text;
Then yes, the setter will copy the value you give it when you invoke:
myTextArea.text = //some string

Objective-C: Share object between two view controllers

I have an iPhone application and I do this in my MyView1Controller:
MyView2Controller *myV2C = [[MyView2Controller alloc] initWithNibName:#"MyView2" bundle:nil];
myV2C.shareObject = self.shareObject;
[self.navigationController pushViewController:myV2C animated:YES];
[myV2C release];
So I push shareObject to the next ViewController. There, in viewDidLoad, I set a property of shareObject like this:
self.shareObject.myText = #"Test String";
So in MyView2Controller, everything is okay, the String is set. But going back to the previous MyView1Controller with the left upper "back" Button, the value of shareObject.myText is not set to Test String.
So, how can I do this? I want to give the View2Controller an object which can be modified, and the modifications I want to have in the View1Controller.
Does anyone know? Thank you in advance & Best Regards, Tim.
OR you can even try using the Singleton pattern
http://www.cocoadev.com/index.pl?SingletonDesignPattern
You can use delegation pattern and/or key value observations
EDIT:
You can achieve this my creating a single object, and then use that object in all classes, wherever you want. For this you can use singleton class, Or you can create a class method. For ex:If I have class A, and I want to push some values in B class, So if I modify the values in B, the newly updated value can be retrieved in a too, or in any other class. In that case, you can create a different class (usually subclass of NSObject),and then write the getter/settor methods in that.
Suppose the name of this newly created class is Manager, then in Manager. m create getter/setter methods, like
NSString *strGlobal;
+(void)setString:(NSString *)strTemp
{
if(!strGlobal)
{
strGlobal = [[NSString alloc] init];
}
//point to same location
strGlobal = strTemp;
}
+(NSString *)getMySavedString
{
return strGlobal;
}
Now In you class A , where you want to send the value to Class B controller, call the setter method to set the value, like: -
-(void)navigateto_ClassB
{
//Setting the value, that should be sent to the other controller
[ManagerClass setString:#"Hello"];
[self.navigationController pushViewController:[[[ClassB alloc]init] autorelease] animated:YES];
}
Now In class B (Or wherever you want to get the saved value, use getter method, like:-
NSString *strSavedValue = [ManagerClass getMySavedString];
No you will have the value, If you want to update the value from anywhere, the again call the setter method, with new value. For ex, i want to update the value in class B, then
[ManagerClass setString:#"Hello Upadted"];
Now this value is updated to same memory location, retrieve it from anywhere using getter method created in Manager class.
As I stated earlier, this is the easiest but not the best approach. Alternatively, you can achieve same functionality with delegate patterns, KVOs (Key value observations) and/or singleton class.
tia was right: "You did it right already, so there must be something wrong somewhere".
It was my fault, so the source code in my question is correct.

Set Multiple Variables to Same Value

I have dozens of NSStrimgs that when the app loads I want to all be set to the same set. All of them. How can I do this without typing out every single one? Is there a shortcut method?
Thanks.
Also the problem is that Josh isn't specific enough about how he's using his dozens of strings... I think this would be better:
NSMutableArray *stringsArray = [NSMutableArray arrayWithCapacity:1];
NSString *tempStr = #"My unique string"; // Thanks Sven!
// Say you want a dozen strings
for (int i = 0; i < 12; i ++) {
[stringsArray addObject:tempStr];
}
// Now you can use them by accessing the array
[self doSomethingWithString:[stringsArray objectAtIndex:8]];
Instead of having dozens of strings that have the same value, could you make a single static global string and reference that? If you need to change it to separate values later, use instance variables that are initialized to the global string.
This sounds like your model is not very good at all. Since you want to initialize all of your strings to the same value they are obviously related and probably should be modeled as an array like iPhoneDevProf described. That makes other things a lot easier too, you can move other code that is repeated for every string into a loop.
If the value is known when you are compiling the code AND it is not going to change after subsequent application sessions then you can use a simple #define.
#define MY_DEFAULT_STRING #"THE DEFAULT STRING"
Now all you have to do is the following.
{
NSString *myString1 = MY_DEFAULT_STRING;
NSString *myString2 = MY_DEFAULT_STRING;
....
NSString *myStringN = MY_DEFAULT_STRING;
}
If all the strings are in the same code file, just put the define at the top. If the strings are in separate code files, then it could be put into your precompiled header. Having a constants file is usually better.
Using constant extern NSString would probably be more correct, but this is simple and easy to do.