1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

class initialization methods: release & alloc

Discussion in 'Mac Programming' started by mdeh, Feb 1, 2009.

  1. macrumors 6502

    May I ask 2 quick questions.
    Given: NSNumber *myNumber;

    myNumber = [ NSNumber numberWithLong: 0xFFAA];

    Question 1:

    Why no alloc?

    Question 2;

    there is no release method. Why is this. Thanks in advance.
  2. Moderator emeritus


  3. macrumors 68040


    This is considered a "factory" method. It:
    Allocates a new object
    Initializes the object with the argument given
    Calls autorelease on the object

    You don't want to call release, because the autorelease pool knows to decrement the retain count the next time it(the pool) is released. If you need to keep the object around after the next time the autorelease pool is released, you can retain it, and run release when you are done.

    Also... There's only 2 bytes there, and a long is 8 bytes long... why not pass in your long with something like:

  4. macrumors 6502

    Lee...thanks as always.
    You have put it in perspective for me..which is what I wanted. Kochan is not yet deeply into the autorelease...but I am sure we will get there.
    So, in general, can we say that , for all the datatypes and objects for which there are factory methods,

    so, I ( the programmer) **normally** ( with the exception you mentioned above) do not worry about alloc/release.

  5. macrumors 6502

    Thanks for your input. I am slowly getting through Kochan's book, so not quite there yet. Your help is appreciated.
  6. macrumors 68040


    Not every class will have factory methods, but some certainly do. Generally if something returns an Object pointer, and it doesn't contain the words init or copy, you'll be getting an autoreleased object. I assume this will be covered in greater depth later in the book.

    As for other datatypes (non-objects, so primitives or structs), none of this applies(edit). I don't know if there are a lot of cocoa methods that return primitive pointers. Most of the time I would expect a value being returned, and you'll just assign it to the same type of variable in your functions. Most of the time primitives will just be local variables in a method, etc. You can deal with C memory management to malloc space for primitives, but this is normally for large arrays not single values. None of the retain/release/autorelease/alloc/init/etc. things that are normally a part of cocoa memory management come into play.

  7. macrumors 6502

    thank you again.
  8. macrumors regular


    Yes it is (there's an entire chapter devoted to it). I would add the word "alloc" to your list.


    Steve Kochan
  9. macrumors 68030


    Also 'new', although not much code uses that these days.

Share This Page