Taking NSString and modifying it for another NSString? - ios

I have a NSString that's giving out input values on a control.
I want to take these values and convert them for user display. AKA, Value 0.7 is 1, value 1.3 is 5. etc.
Ive tried writing an if statement, such as
if self.label.text = 0.7
self.labelone.text = 1
But I cant figure out where it should be written or what code I should be using.
I only need 6 values so even though its a messy way to implement it, I dont mind that much.
Ive searched many resources and I cannot find anything or anyone trying to attempt something similar, which leads me to believe its either incredibly simple, or I'm missing out on something incredibly simple.
Here is the code for the UILabel I'm trying to convert and modify
- (IBAction)rotaryKnobDidChange
{
self.label.text = [NSString stringWithFormat:#"%.3f", self.rotaryKnob.value];
self.slider.value = self.rotaryKnob.value;
}

To compare two variables you should use == instead of =. And you're trying to compare CGFloats with NSStrings.
Use something like this:
if([yourLable.text isEqualToString: #"0.7"]){
[otherLable setText: #"1"];
} else {
if ([yourLable.text isEqualToString: #"1.3"]){
[otherLable setText: #"5"];
}
}

The simple answer to your question:
if ([self.label.text isEqualToString:#"0.7"])
self.labelone.text = #"1";
else if ([self.label.text isEqualToString:#"1.3"])
self.labelone.text = #"5";
But I don't think this is really the code you want.

Related

Objective C - better way to write my if statement [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
It's not an actual problem but it is frustrating me..
I was looking for a better way to right an IF statement with multiple values that can be accepted.
For example:
if ([[myJson objectForKey:#"pages"] intValue] == 0 || [[myJson objectForKey:#"pages"] intValue] == 3)
Isn't there any way to write something like:
if ([[myJson objectForKey:#"pages"] intValue] == 0 | 3)
{
}
Thanks !!
No, not really. You could do this:
int pages = [[myJson objectForKey:#"pages"] intValue];
if (pages == 0 || pages == 3)
That's what I would recommend. The code you posted is both less efficient and harder to maintain than the code I show.
In your code you actually invoke the objectForKey and intValue methods twice on the same object.
Plus if at some point in the future you change the key value, or the variable name, you have to make the same edit in 2 places, which is more work and adds another chance to introduce a new copy/paste error.
In addition to the other valid answers, you could use a switch:
int numberOfPages = [[myJson objectForKey:#"pages"] intValue];
switch (numberOfPages) {
case 0:
case 3: {
NSLog(#"Is 0 or 3");
break;
}
default: {
NSLog(#"Is NOT 0 or 3");
break;
}
}
This is a much better method as it is clean and easier to read:
int x = [[myJson objectForKey:#"pages"] intValue];
if (x == 0 || x == 3) {
}
You are highly optimistic there.
If myJson is not an NSDictionary your app will crash.
If myJson[#"pages"] is not an NSNumber then your app will crash.
If myJson[#"pages"] does not exist then intValue will return 0.
If myJson[#"pages"] has a value of 0.9 or 3.7 then intValue will return 0 or 3.
I suggest you add a category to NSDictionary with a method like integerValueForKey: withDefault where you lookup an item, check that it is an NSNumber with an integer value, return that value or return the default value.
As David Rönnqvist pointed out, it is mostly a matter of preference. I would personally go with NSArray containing allowed values. This way you won't clutter your code with unnecessary intValue calls. Also adding another allowed value will only require adding a single value to an array instead of adding another condition inside if statement.
Note that you can use Objective-C literal syntax to make the code more concise.
NSArray *allowedValues = #[#0, #3];
if([allowedValues containsObject:myJson[#"pages"]]) {
}
If [myJson objectForKey:#"pages"] is an NSNumber. You could do this:
if([#[#0, #3] containsObject:[myJson objectForKey:#"pages"]])
And if myJson is an NSDictionary you could even shorten it to:
if([#[#0, #3] containsObject:myJson[#"pages"]])
It's not necessarily optimal, but it does provide you with a lot more flexibility when adding more values to check against, which it sounds like you're looking for as opposed to the fastest code. If you're just checking a few values I'm assuming speed of execution is not an issue.
Side note: this works because NSArray's containsObject: method calls isEqual: on every object. NSNumber's isEqualToNumber: gets called. This will also work with NSString instead of NSNumber if that's what you're working with. Just change the search array to hold NSString objects in that case.

Displaying two different types of variables in one label string

I am trying to make a CCLabelTTF display a string and an integer together. Like this:
Your score is 0.
I've tried a few things but I usually get the warning Data argument not used by format string, and the label doesn't output the correct statements.
I am just trying to figure out the format in which to put these in and searching Google hasn't provided much, as I'm not really sure what exactly to search.
I've tried
label.string = (#"%#", #"hi", #"%d", investmentsPurchased);
but obviously that isn't correct. How would I do this?
Thanks.
(I assume this is ObjC and not Swift.) Try something like this:
label.string = [NSString stringWithFormat:#"hi %d", investmentsPurchased];
You use a single format string, which contains static text and replacement tokens (like %d) for any replacement variables. Then follows the list of values to substitute in. You can use multiple variables like:
label.string = [NSString stringWithFormat:#"number %d and a string %#", someInteger, someString];
use NSString newString = [NSString stringWithFormat:#"hello %#", investmentsPurchased];
in short: use stringWithFormat

How to fix string in objective-c?

I'm having a problem with the correct answer
When the user types in lets say "dog" the answer is right!
But if s/he types in "dog " <--- with a spacebar its wrong,
how do i fix this:
Code:
- (IBAction)btncheck:(id)sender {
if ([_textbox.text isEqualToString:#"q"]) {
_keyboard.hidden = YES;
_textXclear.hidden = YES;
}
else {
// Was not correct. Notify user, or just don't do anything
}
and id like to notify user that the answer was not correct by placing an image, how is that done
You could use the method stringByTrimmingCharactersInSet to get rid of leading or trailing spaces:
NSString *string = [_textbox.text stringByTrimmingCharactersInSet: whitespaceCharacterSet];
if (string isEqualToString: "q")
{
//string is wrong? If so, display an error message.
}
else
{
//string is correct, resign first responder
}
You should do a search on NSString in the Xcode help system and read the NSString class reference. There are tons of useful methods in the NSString class for doing things like this.
I'm confused, because in your previous post I thought that the answer "q" was the correct answer. In your code above, anything but q would be correct.
As far as placing an image, the easiest thing to do is probably to put an image view, with image installed, in your view controller, but set it's hidden property to YES. Then, when you decide the user has entered the correct answer, set the image view's hidden property to NO to reveal it.

NSArray.count returns incorrect, giant integer

I have the following code, intended to select a random string from the array.
NSArray *popupMessages = [NSArray arrayWithObjects:
#"Shoulda' been bobbin' and weaving! Need anything from the shop?",
#"Don't forget you can use old boss's guns! Available in the shop!",
#"Hey Chaz, you Bojo! You need more POWER! Come by the shop for some better weapons!",
#"Aw… lame. Maybe I got something that can help you out here at my shop!",
nil];
int pmCount = popupMessages.count; // Breakpoint Here - pmCount = 971056545
int messageIndex = arc4random() % pmCount; // Breakpoint Here - same as above
I am using ARC with cocos2d. Any ideas as to why the array's count returns such a huge number? Thanks!
Your problem just looks like it's a debugger artifact. It could be optimization-related, for example. Sometimes compilers can generate code that confuses debuggers pretty seriously. Add a log statement to make sure the debugger isn't just telling you lies.
"count" is not a property, AFAIK.
The way I usually get the count for an array is:
[popupMessages count];
Try:
NSInteger pmCount = [popupMessages count];

Is this the standard way to get text from label and concatenate with string in iOS?

Please bear with me as I'm very new to the world of iOS and Objective-C. I've read Apple's Obj-C primer, as well as a few free ones provided on the web.
On a button press, I'm trying to simply take the text of a label and concatenate it with a string. My mindset is still very much in Android/Java and how simple it could be, but I'm having trouble here. Nonetheless here is my code:
- (IBAction)myButton:(UIButton *)sender {
self.myLabel.text = [self.myLabel.text stringByAppendingString:#"obj-c is hard =/"];
}
It seems pretty standard, but I can imagine myself doing this often so I want to make sure this is correct or what other ways are there to do this?
Yes this is correct way. And if you want to use another method then use this one
self.myLabel.text = [NSString stringWithFormat:#"%# obj-c is hard =/",self.myLabel.text];
It is the standard way to join string.As ios updated syntaxes to make it easy like NSArray and NSDictiornary delaration but for concatenation it has not declared any shortcut way.
Have a look at this
OR
you can use a trick to simplify concatenation of string.Pass a parameter to macro and use following joining literal syntax.
#define STRING(text) #""text""
#implementation SPTViewController
- (void)viewDidLoad
{
NSString *joinedFromLiterals =STRING(#"Congratulations!, ") #"I " #"really " #"enjoy " #"carpenting!";
NSLog(#"joined string %#",joinedFromLiterals);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
output is ---------
joined string Congratulations!, I really enjoy carpenting!
Yes, this is correct, but there is a gotcha. If you haven't previously set the value of self.myLabel.text, it will be nil by default. Then the result of calling any method (like [self.myLabel.text stringByAppendingString:#"obj-c is hard =/"]) will also be nil, so myLabel will still have empty text. The way Objective-C handlesnil values is different than handling null in Java.
So to be safe, initialize label's text first:
self.myLabel.text = #"";
You are doing it right. Sure Objective-C is a bit more verbose than C# or Java or even Visual Basic .net (as I used to work on all those languages) but don't be bugged by those long method names. Although some #defines can be very helpful like (rewritten as C inline function):
static inline __attribute__((always_inline))
__attribute__((format(NSStirng, 1, 2)) NSString *SKSTR(NSString *fmt, ...)
{
va_list args;
va_start(args, fmt);
NSString *string = [[NSString alloc] initWithFormat:fmt arguments:args];
va_end(args);
#if !__has_feature(objc_arc)
[string autorelease];
#endif
return string;
}
Hope the __attribute__s and #ifs does not confuse you - you can safely ignore them.
To use:
self.label.text = SKSTR(#"%#, ugh!", self.label.text); // just like NSLog or snprintf :)

Resources