how to check if an object has been allocated?

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

  1. kamo macrumors member

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

    Example:

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


    Thanks,
    -kamo
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    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.

    -Lee
     
  3. Krevnik macrumors 68030

    Krevnik

    Joined:
    Sep 8, 2003
    #3
    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

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #4
    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

    Joined:
    Mar 21, 2008
    #5
    Thanks, makes perfect sense. I'll initialize to nil.
     

Share This Page