Some favorite site feeds aggregated locally: iPhone Development RSS   Adobe Labs RSS   Macrumors RSS

Thursday, April 2, 2009

A big difference between Objective-C and AS3

Thursday, April 2, 2009   

Objective-C. String comparisons from text controls and normal strings. It's something you just take for granted in AS3.

myText_txt.text = "Hello";
if( myText_txt.text == "Hello" ){ trace("There");}
Easy enough on that string comparison. I thought it would be the same for Objective-C and it isn't. I felt like an idiot for a while today as I struggled with that logic above.

I had a method being called by a UITextField in an iPhone application whenever the value of the field changed.

-(IBAction)editing:(id)sender {
if( field1.text == @"" ){
button.hidden = YES;
} else {
button.hidden = NO;
}
NSLog( @"%@", field1.text );
}
That seems simple enough but it never worked as intended. It's comparing pointers instead of String values. The code below (if it were not for Google, I would have never stumbled upon this myself) does what I wanted.

-(IBAction)editing:(id)sender {
if ([field1.text length] && [field1.text compare:@"Eric"
options:NSLiteralSearch
range:NSMakeRange(0,4)] == NSOrderedSame){
button.hidden = NO;
} else {
button.hidden = YES;
}
}
So what's happening here? We check for a string length to make sure that the compare doesn't blow up with an out of range error. This is essentially the same thing as checking for "" in AS3: if( field1.text != "")... And then there is that compare. I never would have found that myself. The options show how you can check a certain number of characters into the string... and here I should check to make sure the length >= to that range, but I'm not. I should add that.

Anyway, I hope this helps someone save time in their day.

Labels:

 
 Return to the main page
Comments:

There are currently 4 Comments:

Anonymous Chris O said...
“I'm only learning this too, but I believe there is a potential bug in your code if you are trying to ensure the whole string is compared - yours will return TRUE for "Eric Rocks" == "Eric" because only 4 chars are being compared.

Eg. This returns true because it only looks at 6 chars:

NSString *str1 = @"String 1";

if ([str1 length] && [str1 compare:@"String"
options:NSLiteralSearch
range:NSMakeRange(0,6)] == NSOrderedSame){

(Forgive me if I've misunderstood your intent for the code, maybe you meant to compare just the range.)

This line below will compare the whole string (and is slightly easier to remember :) )

if ([str1 isEqualToString:str2]){”
 
Blogger e.dolecki said...
April 4, 2009 7:35 AM
“About the range - I put that in there just to show how you can do it, not that you necessarily should. the compare should work on it's own, as does you isEqualToString method there.”
 
Anonymous Anonymous said...
April 21, 2009 5:30 PM
“You saved my day. Thanks”
 
Blogger e.dolecki said...
April 21, 2009 6:06 PM
“isEqual works too... probably much much easier ;)”
 
 Leave a comment