Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

kamo

macrumors member
Original poster
Mar 21, 2008
34
0
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
 
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
 
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

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.
 
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
 
Thanks, makes perfect sense. I'll initialize to nil.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.