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].
Related
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"];
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.
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
Is there a return type for "any primitive" similar to the way you can use NSObject as the return type for any object? I tried using id, but the compiler was giving me an error that it was trying to convert a primitive to a reference.
Here's what I'm trying to do. :
-(void)setObject:(NSObject*)obj forKey:(NSString*)key {
[sharedInstance.variables setObject:obj forKey:key];
}
-(NSObject*)getObjectForKey:(NSString*)key {
return [sharedInstance.variables objectForKey:key];
}
-(void)setValue:(???)value forKey:(NSString*)key {
[sharedInstance.variables setValue:value forKey:key];
}
-(???)getValueForKey:(NSString*)key {
return [sharedInstance.variables valueForKey:key];
}
The alternative that I have though of is to use separate methods (getIntForKey, getFloatForKey, etc.) to access the values.
1) Read Key-Value Coding Article in XCode documentation - all answers are there
2) There's an object NSValue, which resembles your "NSObject". NSValue can store plain-old-data inside itself.
PS
"Scalar and Structure Support
Key-value coding provides support for scalar values and data structures by automatically wrapping, and unwrapping, of NSNumber and NSValue instance values.
Representing Data as Objects
The default implementations of valueForKey: and setValue:forKey: provide support for automatic object wrapping of the non-object data types, both scalars and structs.
Once valueForKey: has determined the specific accessor method or instance variable that is used to supply the value for the specified key, it examines the return type or the data type. If the value to be returned is not an object, an NSNumber or NSValue object is created for that value and returned in its place.
Similarly, setValue:forKey: determines the data type required by the appropriate accessor or instance variable for the specified key. If the data type is not an object, then the value is extracted from the passed object using the appropriate -Value method."
I would have thought id is the perfect candidate here too... could this just be a casting issue you're seeing?
i.e. the id implicitly implies a pointer so in my mind I see id as an objective c equivalent to the c void*
In other words where you have a NSObject* you could replace this with id such as
-(NSObject*)myMethod1
{
}
so can be done for any returned primitive with
-(id)myMethod1
{
}
i.e. not an id*
Also I expect this was just a copy/paste thing but incase it also causes issues
-(void)setValue:(???)value forKey:(NSString*)key {
[sharedInstance.variables setValue:num forKey:key];
}
should probably be
-(void)setValue:(???)value forKey:(NSString*)key {
[sharedInstance.variables setValue:value forKey:key];
}
I eventually worked through this. The ultimate solution was to have separate accessor/mutator methods per type. So now I have setIntForKey, setBoolForKey, getIntForKey, getBoolForKey, etc. The drawback is quite obvious, in that I can't call one method to set values and another to retrieve them. The advantages are numerous, however. Because the compiler knows what object or primitive type the method is expecting at compile time, I gain compile time checking for all of these methods. Additionally, I don't have to worry with casting the retrieved values to their primitive types (obviously the returned NSObjects are a different story).
I have a class that I use to setup objects in an array. In this class I have a custom "initWithDictionary", where I parse a JSON dictionary. However, as I am running into NSNull, this crashes my app. To get around this, I set up a class that handles exceptions, so when a string is NSNull, it's replace it with #"". or -1 for integers.
This is my NullExtensions class:
#interface NSNull (valueExtensions)
-(int)intValue;
-(NSString *)stringValue;
#end
#implementation NSNull (valueExtensions)
-(int)intValue {
return -1;
}
-(NSString*)stringValue {
return #"";
}
#end
However, in my initWithDictionary method, the following code crashes my app:
self.bookTitle = [[parsedDictionary objectForKey:#"book_title"] stringValue];
It doesn't work regardless of the object in the parsed dictionary being NSNull or containing a valid string. Only if I do the following (and the string is not null):
self.bookTitle = [parsedDictionary objectForKey:#"book_title"];
Is stringValue incorrect in this case? And if so, how do I use it properly in order to setup proper NSNull replacements?
Thx
You really really don't want to add a category to NSNull that adds such common methods. That will change the behavior of NSNull for all instances in the application, including ones created by the underlying frameworks solely for their private use.
If you need a value class that represents the notion of "value doesn't exist and therefore I'm going to return these default values instead", create a class or instance that represents exactly that.
As for why it crashes, I couldn't tell you without seeing the actual details of the crash.
And, yes, it really is THAT bad to add a category to a class that adds such a common method. All it takes is one bit of code in a plug-in or framework that does:
if ([fooMaybeNull respondsToSelector: #selector(intValue)] bar = [fooMaybeNull intValue];
Not terribly farfetched -- I have had to debug nasty crashers or misbehaviors due to exactly this kind of willy-nilly category addition.
If you are going to add methods to a class via categories, prefix your method names so as to isolate them from existing functionality. It is still fragile, but manageably so.
Instead of creating categories on NSNull, for which you would also have to add a similar category to NSString (that's why it crashes, because real strings do not respond to stringValue) - instead try creating a helper category on NSDictionary like "stringForKey" that uses the code Johan posted and returns an NSString, probably also should enforce all other types get mapped to empty strings as well.
The NSNull extensions you have written look ok to me but using a method like stringValue may be confusing since other classes like NSNumber use this.
Personally though, I think NSNull replacement in this instance is unnecessary. If you just made a quick test you can replace the NSNull where you need to. e.g.
id testObject = [parsedDictionary objectForKey:#"book_title"];
self.bookTitle = testObject==[NSNull null] ? #"" : testObject;
You are asking an NSString for its stringValue. No need to convert a string to a string.
Try this:
if (![[parsedDictionary objectForKey:#"book_title"] isKindOfClass:[NSNull class]]) {
self.bookTitle = [parsedDictionary objectForKey:#"book_title"];
} else {
self.bookTitle = #"";
}
Edit: You should not use the category on NSNull you created. You don't need it, nor should you want it. If the source for the dictionary inserts NSNull instances, go ahead and use my code above. Normally you would expect to simple have no value inserted for the key, at which time you can simple see if [parsedDictionary objectForKey:#"book_title"] returns anything.
Are you sure that the dictionary is returning [NSNull null]? By default, dictionaries return nil, not [NSNull null], when an value isn't found for a key.
However, in my initWithDictionary method, the following code crashes my app:
self.bookTitle = [[parsedDictionary objectForKey:#"book_title"] stringValue];
It doesn't work regardless of the object in the parsed dictionary being NSNull or containing a valid string.
That makes sense, since stringValue is not a valid method on NSString. It will work for NSValue and its subclasses, but not NSString.