Reputation: 177
I have class named 'WebServicesiPhone
' .... I want to create an instance of this class and do some json parsing functions and store the result contents into some arrays in the Delegate class ...
how can I declare an instance of this class in some other class ....which is the best way ....
WebServicesiPhone *newsParser = [[WebServicesiPhone alloc] init];
[newsParser getData:0:nil:0:0];
[newsParser release];
or i have to declare a instance in other class's .h file .. like this
WebServicesiPhone *newsParser;
and allocate in method file .. if i am using this method whrere i have to release the object after my use .....
newsParser = [[WebServicesiPhone alloc] init];
Upvotes: 0
Views: 126
Reputation: 1804
If you want the instance variable of WebServicesiPhone
to have class scope and as VdesmedT said if you want to expose the instance variable publicly.You can hide from exposing it publicly by not declaring it in .h
but class extension in .m
to have class scope. Release it after you are done with it. Usually in dealloc, but lets say you alloc init this instance in a - (void)createWebService
and call it over and over again then dealloc'ing it in dealloc method of class isn't proper memory management.
Upvotes: 0
Reputation: 26683
I think you're mixing some terms so I'll try to explain as simple as possible.
WebServicesiPhone *newsParser;
is not an instance, it's a variable. If declared in .h file between curly braces, it's an instance variable, as every instance of your class will have one. If it's declared somewhere in .m file, it's a local variable and will only be available inside the block of code where you declared it.
[[WebServicesiPhone alloc] init];
instantiates a new object of type WebServicesiPhone
, also called an instance, and when you assign value of that to newsParser
, be it instance or local variable, it (newsParser
) becomes a pointer to your class' instance.
So if you have to use this newsParser
all around your code, best practice is to create an instance variable for it (or even a property) and release it in your class' dealloc
method. If you only need it inside one block of code, for example inside init
method implementation, just create a local variable and release it right there once you're done with it.
Upvotes: 1
Reputation: 9113
It all depend if you want to expose the instance publicly. If you don't need that, use local variable as you do in the first sample.
If you use the other method, release the instance in the dealloc method of your class.
Upvotes: 0