views:

934

answers:

5

Hey,

How do I check whether an object already exists or not?

thank you!

A: 

check if it==nil

If you can be more specific, we can give a more specific answer !

Andiih
so that means if i check for exampleif (myButton == nil) {...And is it also possible to check how many instances are existing?Thanks a lot.
rdesign
Actually, it can exist, but just not assigned to this exact variable... This question is too vague.
Adam Woś
A: 
NSObject *someVar=nil;
if(someBool){
     someVar = ...;
}


if(someVar) {
   // will only be executed if someVar has been set and the object exists
}
Felix
A: 

Given the definition

MyClass *myObject;

you simply do

if(!myObject){
   // in this case myObject does not exist
   ...
}
else{
   // in this case myObject exists
   ...
}
unforgiven
+18  A: 

From a comment by OP on the accepted answer:

so that means if i check for example if (myButton == nil) {... And is it also possible to check how many instances are existing? Thanks a lot.

This indicates that you don't understand Objective-C. Start here.

In particular, myButton == nil will check to see if the myButton pointer has a value. Whether or not an object is instantiated somewhere has nothing to do with myButton.

Or, to answer your question above, there is no way to know how many instances of any particular object exist without architected the support necessary to answer that question. I.e. you'd have to write code to make that so.

bbum
+1 first sensible answer to this question
Adam Woś
Certainly the question is vague, but marking down answers that try to make a best guess at the original intent and provide a useful answer in that context doesn't seem appropriate.
mmalc
Agreed w/mmalc.
bbum
I totally agree. +1
Jacob Relkin
+2  A: 

From your comment, you appear to be asking at least two different questions:

so that means if i check for example if (myButton == nil) {... And is it also possible to check how many instances are existing?

  1. Is it possible to check whether a given variable points to an extant object?
    This has been answered by everyone; check whether the value is nil. (Although for complete pedantry, it's also possible for the variable not to be nil but point to an invalid (freed) object.)

  2. Is it possible to determine whether any instance of a given class exists?
    As bbum notes, in general no it is not. You could create your own class that monitors creation of instances of itself if you find you have a need to do so.

It's not clear what you're actually trying to accomplish. Putting 1 and 2 together, it's possible to imagine you're trying to ensure that you create only a single instance of a given class? This is known as the singleton pattern, implementation of which is described here.

If none of these is what you're trying to accomplish, then it would be good of you could rephrase your question...

mmalc