how to check if an object has been allocated?

Discussion in 'Mac Programming' started by kamo, Jul 30, 2008.

  1. kamo macrumors member

    Mar 21, 2008
    Is there a way to check if an object has been allocated?


    NSString *myString;
    - (void)logMyString {
    How can the logMyString function check if myString has been allocated?

  2. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    if you initialize it to nil in the declaration you can check it with ==. If it's uninitialized, there's no good way as I don't think obj-C allows introspection of the runtime.

  3. Krevnik macrumors 68040


    Sep 8, 2003
    Well, Obj-C allows introspection of the runtime (I have abused this in a couple classes to great effect)... the problem is that the runtime doesn't track any master list of objects. It doesn't need to, so it doesn't do it. You could try querying the object using introspection, but the behavior is going to be pretty undefined. A non-nil pointer that isn't an object could lead to weird behavior you don't want.

    I would do the standard thing and just initialize it to nil, and check that the pointer isn't nil. This is general practice in C, C++, Obj-C, and even C# or Java.
  4. lazydog macrumors 6502a

    Sep 3, 2005
    Cramlington, UK
    If the pointer is an instance variable it will be initialised to nil for you when the parent object is allocated… but a local variable needs to be initialised to nil if you want to check it later on.

    b e n
  5. kamo thread starter macrumors member

    Mar 21, 2008
    Thanks, makes perfect sense. I'll initialize to nil.

Share This Page