Hey,
How do I check whether an object already exists or not?
thank you!
Hey,
How do I check whether an object already exists or not?
thank you!
check if it==nil
If you can be more specific, we can give a more specific answer !
NSObject *someVar=nil;
if(someBool){
someVar = ...;
}
if(someVar) {
// will only be executed if someVar has been set and the object exists
}
Given the definition
MyClass *myObject;
you simply do
if(!myObject){
// in this case myObject does not exist
...
}
else{
// in this case myObject exists
...
}
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.
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?
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.)
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...