Which is the best way to create a instance of my Class in IOS - objective-c

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];

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.

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.

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.

Related

Self contains Self property [duplicate]

This question already has answers here:
What is the purpose of the -self method in NSObject-conformant classes?
(3 answers)
Closed 8 years ago.
I was messing around with Objective-C and I stumbled upon something strange. The following code compiles and works the way I want it to.
self.scrollView.delegate = self.self.self.self.self;
// equivalent to = self;
Why does this compile? Is it the case that self is a property of an object. If so, I have never seen self declared as a property. I thought self referred to the instance of the class you are creating.
Let me turn this around Why shoudn't it compile nor work as expected?
self is a property of NSObject. It always points to the object itself. Every object inheriting from NSObject has it.
As you say, self refers to the instance. Well, it is not only valid in the context of creating instances. It is always there. And it is very helpful.
[self myProperty] or self.myProperty refers explicitely (laugh more or less explicitely but it does) to the getter (or the setter) of the property myProperty while just typing myProperty within a method refers directly to the property without passing the getter.
Another example is someOjbect.delegate = self; or so.
So, as self alsways refers to an object, to the very object, it has a self property that refers to the very object which has a self property ...
BTW, classes are objects in Objective-C that inherit from Class. In the context of a class, i.e. in class methods, it refers to the class object of the very class. You can play the same game there. If you start off with an instance, then you can play the game with the class property.
self.class.class.class == [self class].self.class.self
should evaluate to YES. (Well, I never tried that myself. If you actually try it and find this wrong, then please let me know)
self is a method in the NSObject protocol. It returns the object it is called on, it is rather pointless.
This is distinct from the local variable self, which within a method refers to the object the method was called on.
Both the method and the local variable apply to class objects as well as standard instances, so a class method has a self local variable and a class object a self method.

Declaring or not declaring in Objective c

I'm starting with obj-c and there's a few things I don't get.
First of is I (oh I'm coming from an AS3 coding perspective) thought that if you wanted to have a variable in your class, you needed to declare it first in the header with the #property operator, and then #synthesize in the .m file, and also you had to declare the method in the header as well, but I've come across situations where variables are just defined in the methods in the .m file, without any declaring anywhere, and the same for the methods, methods that are just written straight into the .m file with no declaring and they work fine.
So what's the point of the #property/#synthesize for variables and declaring the methods in the header files? it is all to do with scope?
What you are talking about is not referred to the declaration of a variable but to expose it from outside of the class through a getter and a setter.
The #property/#synthesize are just a shortcut to automatically create two methods which are
- (void) [class setVariable:(type)var]
- (type) [class variable]
that can set and get the variable from other classes.
Not every variable needs to be set or got from outside the class.
The header (.h) file should contain what you want other classes to know about this class. A class extension -- an interface section inside the .m file -- is a good place for private declarations. (If a method is defined before it is used, that serves as a declaration. It isn't optimal but it works.)
There are three main categories of variables in Objective-C:
Instance variables
Static-scope variables (static, global, and function-static)
Automatic-scope variables (locals and function/method parameters)
When you declare and synthesize a property, an instance variable is created for you. Local variables, on the other hand, are declared in the scope of a code block, and cannot be declared through a property.

Where should I initialize variables in objective c?

In objective c, should I overwrite the init method to initialize my variables? If the variables are properties can I still access them the usual way to set their initial value?
In objective c, should I overwrite the init method to initialize my variables?
Yes. Specifically, the designated initializer(s).
Your subclass may also specify another construction stage (e.g. viewDidLoad). Also, the object's memory is zeroed when it is allocated, so you do not need to set them explicitly to 0/nil (unless you find it more readable).
If the variables are properties can I still access them the usual way to set their initial value?
You should avoid using the object's instance methods/accessors, and access ivars directly in partially constructed states (notably the initializer and dealloc). There are a number of side effects you will want to avoid - Example Here;
you can initialize you variables in viewDidLoad method of a view controller.
Variables declared in the classes interface will automatically be initialized to there default value, 0 for integral values and nil/NULL for classes and pointers. If you need to initialize the variables to other values then you need to override a guaranteed entry point for you class. A custom class inheriting from NSObject for example you will simply override init. If you are working with a view controller loaded from a NIB file then you could override initWithCoder: or – awakeFromNib. You should always check the documentation for whichever class you are inheriting from and find the designated initializer for that class. Sometimes you will need to set a common initializing method and call it from various initializers. Also if you have a variable that is also a property it is recommended that you should set the property and not the variable directly.
should I overwrite the init method to initialize my variables?
Instance variables: yes, although they are by default initialised to 0/nil/false already.
If the variables are properties can I still access them the usual way to set their initial value?
Yes you can. Apple advises against it because of the danger that a subclass has overridden the set accessor to do something unexpected. In practice, this is rarely a problem.

Objective-C: Should init methods be declared in .h?

First of all, as I understand it, init in Objective-C, functionally is similar to a constructor in Java, as it is used to initialize instance variables and prepare a class to do some work. Is this correct?
I understand that NSObject implements init and as such it does not need to be declared in any .h files.
But how about custom implementation of init for a given class, for example:
(id) initWithName:(NSString *) name
Should declaration like this be listed as part of .h, or it is not necessary? Is it done by convention or is there any other reasoning?
init is by no means similar to constructor in Java/C++. The constructor always executes when the object is created. But the execution of init is up to you. If you don't send init message after alloc then it will not execute.
// init does not execute here
MyObject *obj = [MyObject alloc];
And this will work without any problems if you derive from NSObject, as init of NSObject does nothing.
You do not need to add init in the header file, because it is inherited from NSObject but you need to add custom init methods (that are not inherited) to the header file. Note that init methods are just normal methods with a naming convention, but technically there is no difference from other methods.
If you do not specify your custom init methods in the header file, but send that message to an object, the compiler will generate a warning. There will be no compile error. So if you decide to ignore the warning then you can omit that from header too. But you will get a runtime crash if the method is not actually implemented. So it's better to add all methods that are not inherited in header file.
Yes you have to declare it if you want to be able to call this personalized initialisation method (initWithName). And the first think you have to do in that method is to call [super init];.

Accessing an object outside scope in a controller class

In my controller class, I initialize two instances of a model class (whose header is properly imported into controller class) with an NSButton. The model is really simple, just 4 members and one method - attack(). Making a silly text game!
- (IBAction)startGame:(id)sender {
Combatant *hero = [[Combatant alloc] init];
Combatant *enemy = [[Combatant alloc] init];
[console insertText:#"You have created a hero! An enemy approaches...\n"];
}
So now I have these two objects sitting there. Or do I? Because this other button, the one that's supposed to make them fight, has no idea what hero and enemy are, or that they have a class method that makes em' fight!
- (IBAction)attack:(id)sender{
[hero attack:enemy]; //Use of undeclared identifier, blah blah.
[console insertText:#"You attack the enemy! Woah!\n"];}
I get that if I initialized those objects in the attack method, then I could use them, so I gather this is something to do with scope. But I don't like the idea of sending model objects to controller methods, that seems silly.
Let me apologize: yes, this is a stupid, high-level question about the structure of Cocoa. Sorry. But I figure one of you will know exactly what I am not doing and tell me to do it!
In short, what is the Cocoa way of doing things in this situation? Thanks in advance.
-Alec
When you declare a variable in a method, it is a local variable, which means it only exists in that method. The same goes for variables you declare in functions.
If you want the variable to exist in all instance methods in the class, you need to make it an instance variable, which you do by declaring it in that { … } section in the class's #interface.
Note that any objects you store in instance variables, the instance should own. This means three things:
You'll need to either retain the object (and thereby own it) or make a copy (which you will then own) before assigning it to the instance variable.
Since you own it, you'll need to release it in the instance's dealloc method.
If you decide to replace it with a different object, you'll need to release the former object (since you still own it) and retain or copy the new object (in order to own it).
See the Objective-C Programming Language and the Memory Management Programming Guide for more information.