Memory Management

Discussion in 'Mac Programming' started by Garrett, Jul 13, 2008.

  1. Garrett macrumors regular

    Apr 4, 2007
    I am in migraine pains over this topic (somewhat sarcastic), how do I know when I need to allocate memory to something? When to release it? It's a confusing subject that is hindering my process of functioning. (Because that's all I think about :rolleyes:)

    Are there examples when you need to use it, and when you don't need to use it? Are there examples when you think you should but it's dangerous to do so? :(
  2. Duke Leto macrumors regular

    Mar 17, 2008
    Which language? I know that in Objective-C, memory management isn't something you turn 'on' or 'off', but instead your RAM is like a room: pick up after yourself and it should still be clean.
  3. Garrett thread starter macrumors regular

    Apr 4, 2007
    Yes, in Objective-C.

    But do I even store NSStrings on RAM? :confused:

    I am confused about every detail of it. :(
  4. kpua macrumors 6502

    Jul 25, 2006
    If you're confused this much, you need to review some basic memory management principles before diving in.

    Effectively everything that your program uses is stored in RAM. Every object that your program uses takes up RAM, which should be freed at some point after it is no longer being used.

    Objective-C uses a reference counting mechanism to manage the allocation and deallocation of memory. There are plenty of threads on this forum and excellent documentation from Apple regarding how this works.
  5. Duke Leto macrumors regular

    Mar 17, 2008
    NSString *someString = [[NSString alloc] init];
    [someString release];
    There, in those lines of code you allocated memory for the string, and you removed your reference to it. That, and autoreleasing your variables as they return from methods are basic forms of memory management.

    Example of autoreleasing:
    - (NSString *)someFunction
         return [someString autorelease];
    That releases the someString variable sometime after you call autorelease. (Of course this is just an example, you would actually have to have a 'someString' variable in this method for it to work without error.)
  6. Garrett thread starter macrumors regular

    Apr 4, 2007
    I have understood that much, I just don't know when to use it is my main concern. So you just use the class name? Also, how would I be able to specify a value to the NSString?

Share This Page