hot do i make a comparison of integers and values of text box in Objective C - iphone

i'm new to iphone programming and i encountered/noticed some problems while i was coding. which was after i typed a statement like
if (label.text > label2.text) {
do something...}
however, after typing my application can be compiled and run however when i try to validate it by comparing the values, my specified actions can run and i can change my image view image, however the conditions is not true but the specified actions can be run. Do enlighten me thanks! i will post my codes at the bottom, do comment if you spot any better practices? thanks once again.
Oh and how can i specify to check in my label that the default value is not "Label" or empty because i would like the values to be populated with number before commencing.
-(IBAction) beginMatch {
if (resultP1.text, resultP2.text = #"Label") {
errorMsg.text = #"Please Press Roll (:";
}
else
if (resultP1.text > resultP2.text) {
MG = [MainGameController alloc];
MG.player1 = playerName.text;
}
else {
MG.player1 = playerNameP2.text;
}
[self.view addSubview:MG.view];
}
this is one example that it does not work i have another one which is below.
-(IBAction) btn:(id) sender {
ptc = [playerTurnController alloc];
if (ptc.player1name = MGplayerName.text) {
if (lblDiceResultP1.text > lblDiceResultP2.text) {
img.image = [UIImage imageNamed:#"yellow.png"];
}
else if (ptc.player2name = MGplayerName.text) {
img.image = [UIImage imageNamed:#"Blue.png"];
}
}
}
Thank you.

Your code contains quite a few errors. You're trying to compare NSString values with ">", you're using the comma operator and = operator incorrectly, and you're allocating new objects in (what look to be) the wrong places.
You really should work your way through the introductory documentation on Apple's developer website first:
Learning Objective-C: A Primer
and
Your First iPhone Application

In here you're comparing string (alphabetically) addresses:
lblDiceResultP1.text > lblDiceResultP2.text
You probably want to extract NSNumbers of out the strings and compare the numeric values.
This here is an assignment and not a comparison:
ptc.player2name = MGplayerName.text
You probably meant to use == which is also wrong.
NSStrings are compared with the isEqualToString e.g.
NSString * s1 = #"String One";
NSString * s2 = #"String Two";
if([s1 isEqualToString:s2])
// do something when strings are equal

Related

combine UITextFields input into one UITtextField

Im new to xcode and objective c. I have asked this question three times and still can't find a good method or answer. I have several uitextfields that accept user input and adds it to the combinedtextField in order of IBAction used.ie user inputs big in one field,bad in the next one and boy in the third and the result is big bad boy in the combinedtextField.
-(IBAction)addtextField1: (id)sender
{
combinedtextField.text = [NSMutableString stringWithFormat:#"%# %#",
combinedtextField.text,textField1.text];
}
-(IBAction)addtextField2: (id)sender
{
combinedtextField.text = [NSMutableString stringWithFormat:#"%# %#",
combinedtextField.text, textField2.text];
}
-(IBAction)addtextField3:(id)sender
{
combinedtextField.text = [NSMutableString stringWithFormat:#"%# %#",
combinedtextField.text,textField3.text];
}
Now this is where it gets interesting.I need to be able to remove the selected text from the combinedtextField.
-(IBAction)removetextField1:(id)sender
{
//////////????????????////////////////
}
-(IBAction)removetextField2: (id)sender
{
//////////????????????////////////////
}
-(IBAction)removetextField3: (id)sender
{
//////////????????????////////////////
}
If I tap the removetextField2 button it would remove the corresponding text(bad) from the combinedtextField and then it would read (big boy)
Ive looked into nsarrays,nsdictionarys and other methods and have got no where.
Need some way of possibly tagging the input and removing it that way. Example code would be great and very much appreciated.
You've left out some important details about your app, so I'm making some guesses about how it should work.
Perhaps what you should do is keep a mutable array of all of the fragments that have been added to the combined string:
#implementation MyViewController {
    NSMutableArray *fragments_;
}
- (void)viewDidLoad {
[super viewDidLoad];
fragments_ = [[NSMutableArray alloc] init];
}
When one of the add buttons is tapped, you append the corresponding field's text to the array and recompute the combined string:
- (IBAction)addTextField1:(id)sender {
[fragments_ addObject:textField1.text];
[self updateCombinedTextField];
}
- (void)updateCombinedTextField {
combinedTextField.text = [fragments componentsJoinedByString:#" "];
}
When one of the remove buttons is tapped, you try to remove the corresponding field's text from the fragments array and recompute the combined string:
- (IBAction)removeTextField1:(id)sender {
[fragments_ removeObject:textField1.text];
[self updateCombinedTextField];
}
That will remove all occurrences of field 1's text from the fragments array. If you just want to remove one instance, you will need to use indexOfObject: (or one of its variants) followed by removeObjectAtIndex:.
You can't do it in a very trivial way (without anything to add, just 1stroke magic function). But, there's the easy way, which i'd possible gone for.
If you don't need to do it a lot of times, and / or the text is quite small (not like a 500 pages book), then:
Create a boolean array named mark, and mark[i] should mark the i'th text field as 'added'. Then, create a function named reloadCombinedTextField, which creates it again, depended of the mark array. (if mark[i] == true, then we add a textfield's text, otherwise not)
Then, just mark or unmark the needed text fields in every function and call the reload function in the end of every call.
Altho, there is another way, but it can be wrong in situations where your text fields have the same text. The thing is, you just search in your combined text field the text from selected text field (for example, with [NSString rangeOfString] method) and remove it.
If you are going to do it often and the text is really big, then it goes much more complicated. But i'm quite sure, that you won't do this on iOS.

Writing a for loop in Objective C way

I have a doubts in writing a for loop in Objective C way. I can do the same loop in traditional C for loop, However I am trying to learn Objective C. Here is my question.
listdata is a mutable array holding objects of ofi_vc_modal_ab_user_info objects, I want to compare each email of list data with email until list data count and find its position and if found I want to delete the object from list data.
for (ofi_vc_modal_ab_user_info *loc_obj in listData)
{
if (strcasecmp(loc_obj->email, email) == 0) {
// What need to do here.
}
}
How to proceed here... thanks for your helps :)
you can just use C's for.
in fact, it's an error to mutate the collection you iterate over when using for (e in collection).
BOOL foundObject = NO;
ofi_vc_modal_ab_user_info *loc_found_obj = nil;
for (ofi_vc_modal_ab_user_info *loc_obj in listData)
{
if (strcasecmp(loc_obj->email, email) == 0) {
// Set your flag here
loc_found_obj = loc_obj;
foundObject = YES;
break;
}
}
if(foundObject) {
// Do your stuffs as object is found
// Your found object is in loc_found_obj
[listData removeObject:loc_found_obj];
}
I hope below code explains what you want. Please explain bit more if you need more help.
EDIT : If you are using NSMutableArray then you do not need index of the object. you can directly delete object as mentioned in my edited code.

Restricting what is passed into a method

Right lets say I have a method something like :
- (void)doStuff:(NSString *)doStuffWith;
Can I make it so that doStuffWith will only accept certain words like lets say "DoSomething1" and "DoSomething2", so when i call it like :
[self doStuff:#"DoSomething1"];
it will run but if I call it like :
[self doStuff:#"HelloWorld"];
it will give a warning or something?
You should use an enum, like:
typedef enum {
MyStuffOne,
MyStuffTwo,
MyStuffThree
} MyStuff;
- (void)doStuff:(MyStuff)stuff;
thus you will be able to pass only "MyStuff" (MyStuffOne, MyStuffTwo, MyStuffThree)... these are integers and if you want to play with strings, in your method you have to do something like:
NSString *string;
switch (stuff)
{
case MyStuffOne:
string = #"StuffOneString";
break;
default:
...
}
If you need to limit amount of possible values, you should use enumeration data type instead of NSString
Why not just add an if statement into the method like this
- (void)doStuff:(NSString *)doStuffWith{
if([doStuffWith isEqualToString:#"DoSomething1"]){
//do whatever you want here
}else{
//add your warning here
}
}
That should work fine
You could create a method that checks if a word is valid and then assert that method returns true. That would then crash the app if a programmer ever called the method with a bad string, but wouldn't really help if users are able to enter strings themselves. Also, if you use the default project settings, assertions only happen when building with the Debug configuration.
For example:
static NSSet* __validStrings = nil;
- (BOOL)checkString:(NSString*)string
{
if( [string length] == 0 ) return NO;
static dispatch_once_t token;
dispatch_once(&token, ^{
// build the list of valid words once, or load from a plist or something
// if they are very large or change often
NSArray* validWords = [NSArray arrayWithObjects:#"valid", #"doSomething", #"etc.", nil];
__validStrings = [[NSSet alloc] initWithArray:validWords];
});
return [__validStrings containsObject:string];
}
// your doStuff implementation
- (void)doStuff:(NSString*)doStuffWith
{
// This will crash the program and give you debugging information if doStuffWith
// is not in your string list
NSAssert1( [self checkString:doStuffWith], #"invalid string: %#", doStuffWith );
// continue on with your method implementation...
}

Objective-C: Comparing normal strings and strings found in NSMutableArrays

I am confused about strings (a beginner's problem, I'm afraid):
I have one NSMutableArray called Notebook. At index position 1, I have an object, which I think is a string. At least I put it into the array like this:
[NoteBook replaceObjectAtIndex:1 withObject:#"x-x-x-x"];
So far so good. If I put this into an UILabel, it will show x-x-x-x on my screen. The nightmare starts when I try to compare this string with other strings. Let's consider that I do not want to display the string x-x-x-x on my screen, but just to have a blank instead. So I thought I could achieve this by coding this:
NSString *tempDateString;
tempDateString = [NSString stringWithFormat:#"%#",[NoteBook objectAtIndex:1]];
if (tempDateString == #"x-x-x-x") {
UISampleLabel.text = #"";
}
For some reason, this does not work, i.e. even if the string at position 1 of my array is 'x-x-x-x', it will still not set my UISampleLabel to nothing.
I suppose that I am getting confused with the #"" markers. When do I really need them? Why can't I simply code tempDateString = [NoteBook objectAtIndex:1]; without the formatting thing?
Any help and suggestions would be very much appreciated!
You need to compare string with isEqualToString:
if ([tempDateString isEqualToString:#"x-x-x-x"]) {
UISampleLabel.text = #"";
}
In addition to the question that's been answered:
Why can't I simply code tempDateString = [NoteBook objectAtIndex:1]; without the formatting thing?
You can. Why do you think you can't?

Having a problem with simple bool

I've some really simple code that checks if my bool is == YES but it does not ever enter.
NSLog(#"boool %d",self.arrayAlreadyPopulated );
if (self.arrayAlreadyPopulated == YES)
{
Match *aMatch = [appDelegate.matchScoresArray objectAtIndex:(numMatchCounter)];
aMatch.teamName1 = TeamNameHolder;
}
else
{
Match *aMatch = [[Match alloc] init];
aMatch.teamName1 = TeamNameHolder;
[appDelegate.matchScoresArray addObject:aMatch];
[aMatch release];
}
The debug at the top says that the value of self.arrayAlreadyPopulated is 1 on the 2nd pass as it should be.
But it never enters the first first part but jumps down to the 'else'
I cant see for the life of me what the problem is. -.-
Anybody able to clue me in?
Thanks
-Code
EDIT declaration code
BOOL arrayAlreadyPopulated;
#property (nonatomic) BOOL arrayAlreadyPopulated;
#synthesize arrayAlreadyPopulated;
Don't compare a BOOL against YES or NO. They can carry values that are not NO but don't compare equal to YES. Instead, use the boolean expression directly in the if statement:
if (self.arrayAlreadyPopulated)
{
// ...
}
arrayAlreadyPopulated is probably not actually a BOOL. If, for example, it was a float, the %d would still print 1.
Check and double check that you're assigning the value to arrayAlreadyPopulated always as self.arrayAlreadyPopulated = YES instead of just arrayAlreadyPopulated = YES.
Sometimes, using the property v/s the associated variable of the property interchangeably doesn't always work out the way you'd expect it to. Use the "variable" name only if you're using it to release memory by [variable release] statement, just the way you'll find it in any Apple example code. In all other cases use self.propertyname.