Using NSString

NSString and Numbers

One of the things we used to keep forgetting it how to turn an NSString object into an integer (or a float) - 

int i   = [sMyString intValue];

float j = [sMyString floatValue];

And, if you have some numbers and want to turn them into a NSString? Just like this,

sMyString = [NSString stringWithFormat:@"An int %d and a float %f",iMyInt,fMyFloat];


Is NSString empty?

Sometimes we need to know if a NSString is empty, so we use the length like this -

if([string length] == 0) 
  {
  // string is empty or nil
  } 

But, sometimes we also need to know if the string is just full of whitespace too, we do that like this -

if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) 
  {
  // string is all whitespace
  }

Simply put the two together in a function to test for emptiness or whitespace!


US iTunes, App Store, iBookstore, and Mac App Store
© FiddleMeRagged 2012