String madness Objective C

Discussion in 'Mac Programming' started by MasterObiWan, Jan 19, 2009.

  1. macrumors newbie

    So even trying to do a simple thing like getting an index of a string is not easy in objective C.

    with characterAtIndex I get handed the unicode of the string, so their must be a method to convert the unicode to string.

    Were the people who created objective C kind enough to include a method to convert a unicode back to a string, or must I take out the unicode chart and do it all myself?

    int hi = [@"hello world" characterAtIndex:1];
    textView.text = [NSString stringWithFormat:mad:"%d", hi];
  2. macrumors 6502a

    Have a read of this article - it might help. By the way, I'm no expert I was just intrigued by your posting and did some googling. There may be better articles/explanations/guidance available from others.

    In short, it seems a bit messy... :(

  3. Moderator


    Staff Member

    This looks pretty dangerous to me: characterAtIndex returns a unichar, not an int. Whilst this may well work, I'd say it's not a good idea...

    And NSString does provide a way of turning an array of characters into a string: stringWithCharacters:length:. Just add you character to a unichar array with a single element and call this with length 1.
  4. macrumors newbie

    A character is not a string, hence the names of the methods. (But I agree that it's confusing at first.) If you really want to get part of a string, use the "substring..." methods.
    NSString *helloFirstLetter = [@"Hello" substringWithRange:NSMakeRange(0,1)];
    As far as I can tell, the "characters..." methods are there for when you need to work with textual data that is not already an NSString and/or cannot easily be converted to one by the factory methods. From the linked article:

  5. macrumors G5


    What do you actually try to achieve?

    There are lots of methods that manipulate the contents of a string, and they are usually there for some reason.
  6. macrumors newbie

    These posts helped very much, I finally understand now why my program was crashing into pieces.

    For some reason when I looked at the return value type "unichar" for characterAtIndex I thought it meant it would return unicode :rolleyes:.
  7. Moderator


    Staff Member

    Erm, it does. It means it's returning a single Unicode character.
  8. macrumors newbie

    I meant the decimal code for it.

Share This Page