NSString cString or UTF8String

Discussion in 'Mac Programming' started by idelovski, Oct 22, 2008.

  1. idelovski macrumors regular

    Joined:
    Sep 11, 2008
    #1
    How are these methods implemented?

    Utility methods that return objects send them autorelease message first, but cString does not return an object, it returns a c string. It is just a block of memory. That memory is allocated by the method and yet, the caller (message sender) does not need to release it.

    If I wanted to write a similar method, how would I do it?
     
  2. Guiyon macrumors 6502a

    Joined:
    Mar 19, 2008
    Location:
    North Shore, MA
    #2
    IIRC, the cString method is just returning a (const char*) which you should only be using for short read-only work or copying.

    The NSString class handles the allocation and freeing of the space internally; once the main NSString object is dealloc'd it also frees the allocated space for the cString so if you didn't copy it and you are still using it you'd get garbage. The same thing applies to the UTF8String method.
     
  3. idelovski thread starter macrumors regular

    Joined:
    Sep 11, 2008
    #3
    Actually, I expected there is some magic that frees that memory before the NSString object gets released.

    So, if I was about to implement something similar, a method that returns a block of memory, I'd set some char buffer to NULL in -init method, allocate and fill it in my equivalent of -cString method and free that memory on final release. Hm - no magic this time.

    In other words, if I'm dealing with an object that will have a long & healthy life and if I want to give back to the system those internal buffers in my hypothetical class I would need some -freeTemporaryBuffers method.

    Thank for the reply.
     
  4. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #4
    These methods are not guaranteed to succeed. If they do succeed, they will usually have to allocate memory and convert from whatever format the NSString used internally; the memory will go away inside [NSString dealloc].


    Use malloc/free together with getCString; that would be reliable.
     
  5. idelovski thread starter macrumors regular

    Joined:
    Sep 11, 2008
    #5
    On top of that, both cString and getCString are deprecated. Method -getCString:maxLength:encoding: seems to be the answer.
     

Share This Page