The Ins and Outs of Setters and Getters in iOS? [closed] - ios

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
From what I can understand setters and getters are used to set variable values from outside of the class scope. This seems useful as you may want to hide code using encapsulation.
However surely this method goes against encapsulation theory as you are injecting and manipulating values from outside of the class?
When are the correct times to use setters and getters in OOP? (any analogies would be great)
Are they defined in the main file or the interface file? As it seems like you would want to define a setter and getter in the .h file as you then set the variable's actual use in the .m file.
Lastly, why do you see getter methods simply returning the variable that they are getting? surely this is already done by the main file implementation.
Overall I just want a real clarification of getters and setters and why they are so useful.
Thankyou

If you have both - setter and getter - for one variable, it is true, that you can change it outside your class.
There is right question - why to do that?
Because of reusability and "agility" of your code.
1)Checking for right input
If you want to set age of person, you can check if the value is greater than zero in setter.
2) Reusability
Imagine that you create program which (among others) connect to server, receive array of bits and it creates integer from that array. Then you do something with that integer, you set this value from several places.
But server changes sending from little-endian to big. If you used setter and getter, you can change setter to transform it right before saving it. Or you can change your getter for giving right output.

Let's say there's no "wrong" time to use setters and getters because they give you additional control (memory management etc). As libik mentioned validation of values is really important to prevent your program from "falling" into an inconsistent state no matter if you set a self-calculated value or user input. And using setters often does not just mean storing a value in an ivar but might lead to other actions being necessary when setting a value. Hiding code is important as you don't want to make all actions behind the scenes obvious to public. And a setter also gives you the chance to return e.g. a boolean value representing if the value could be set properly or not.
A getter gives you the oppurtunity to lazily instantiate an object "on demand" if it hasn't been done yet instead of always creating objects supposing they could be needed later.
- (Object *) myObject {
if (!_myObject) {
_myObject = [[Object alloc] init];
}
return _myObject;
}
It's up to your needs whether you define your setters and getters in the interface of the .h or .m file. There might be a case in which you want your setter to be private (in .m file) and only make your getter public because the value is beeing changed inside your implementation depending on certain state changes or vice versa.

Related

Difference between self.view.addSubview and view.addSubview

I have done a bunch of coding in swift and prefer to do a lot programmatically and I was wondering what the difference was between these two:
self.view.addSubview(someNewView)
view.addSubview(someNewView)
they both seem to work. Is one better for some reason? Are they actually that different?
If this is a dumb question or already answered it can be removed. Just a thought.
There's no real difference, although you may see the use of self more often from previously Objective-C developers. From the docs:
In practice, you don’t need to write self in your code very often. If
you don’t explicitly write self, Swift assumes that you are referring
to a property or method of the current instance whenever you use a
known property or method name within a method.
...
The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way.
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

Somes questions about Objective-C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a student in a internship, and i'm learning Objective-C in order to develop an IOS application. They already had an existing base of code, but some part of the code give me problems.
As the previous developer isn't in the company anymore, and because no one else know about Objective-C, no one can answer some of my questions about how the application is built, so I can't determine if it is that i don't understand, or if it's just bad practices.
Here are these questions :
1°) In some classes, i found code like this :
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated] }
This code is useless, right ?
2°) In like 9/10 methods in the project, they return (void). Is it a common pratice in Obj-C (because everything is a pointer) ?
3°) Sometimes there is the interface declaration in both header and messages files. I guess it's because you want to declare only a part in header for a future include, and to have a "private" part. But in a file, i find the following code :
In header :
#interface WebViewController : UIViewController
#properties ...
#end
In Msg file :
#import ...
#interface WebViewController ()
#end
#implementation WebViewController ...
What's the point declaring a void interface a second time in the msg file ?
4°) More, in another class, the interface is declared a second time too, but a method is defined (in the msg file). What's the point as the method is defined bellow, and is not declared in the header file ?
thank you in advance
Welcome to Objective-C :)
Not necessarily. The super class may have specific behaviour defined in it's own method implementation that would cause an issue if you didn't call it. Overriding methods means the super classes own method won't be called by default.
Added from comment: Of courser if you didn't override it then the superclass definition would get called just fine. There are 2 common reasons why you would find it overridden:
a. It's in the Xcode template so it has always been there and not been removed
b.it used to have other content but it was deleted and the method call left behind.
Yes. Although you don't explicitly return void in the method, you do need to specify some return type. If you're not returning anything then void is the right value. It's found commonly in obj-c classes as the method may respond to being called by mutating an internal ivar or property and not require a return. Alternatively the result might be to send a notification so a return value is not needed. Increasingly the use of block-based completion handlers replaces explicit value return as a way to respond to the contents of a method.
Yes, it's to give a private interface that you don't want exposed. In the case where there's nothing in the private interface it's probably there because it came with the template code from Xcode and no one removed it. You can ignore or remove.
For the one you mention with a method, while it's not required to declare private methods in an interface it makes sense from the point of view of writing readable code (a strongly endorsed concept in obj-c). Since the compiler will remove any unnecessary code it makes no difference to declare it and makes the task of reading the code and understanding the class that much easier when you or someone else returns to it later. It's a also a good place to put documentation in comments as it groups it all together.
Hope that helps. Check out the Objective-C programming guides from Apple to for more best practice tips.
1). Yes you can delete this method
2). It depends upon your requirement, whether you want a return type or not. e.g.
- (BOOL)isEmptyOrNull:(NSString*)str;
3). These are called extensions, you can read more about it here http://rypress.com/tutorials/objective-c/categories.html
Extensions are used to hide the methods from out side world(by saying hide I mean you can't find those methods with your eyes)
4). Methods define in implementation file are not visible to a programmer, it's just like private methods in java but in ObjC there is no such thing like private method. Read this thread for private methods Best way to define private methods for a class in Objective-C

General questions on Xcode iOS 7 Objective C [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm following the Stanford Developing iOS 7 course 2013 2014 on iTunes U (just for your info) and I'm having some general questions on the Objective C language. Thanks for your help!
Question 01
This is what I understood about #synthesize:
With the newest versions of Xcode there is no need to perform #synthesize for declaring a setter or a getter. It is done automatically for the programmer if the getter and setter is kept at default. However I have been taught I need to declare the synthesize when overrides BOTH the getter and the setter.
My question is: why only when BOTH are being overriden? It should make more sense to me you would need to declare the synthesize already when only one needs to be overridden?
Question 02
- (void)addCard:(Card *)card atTop:(BOOL)atTop;
- (void)addCard:(Card *)card;
Are 2 different public methods used in the course I'm following.
Question: Am I required to state these two as 2 individual methods. Couldn't I just use the first one, whilst specifying 2 different blocks of code to perform, by an IF ELSE clausule whether the BOOL is YES or NO? Wouldn't that be exactly the same outcome?
Question 03
Having a rather simple program with just a single view, I noticed I do not need to publicly specify any methods in my viewcontroller.h. I reckon this only would be needed if your program is more complex and contains several MVC where the controllers would need to "speak" to each other. Is this a right assumption to make, generally speaking, when making a proper MVC based program?
I thank you for your time and effort. Excuse me if my questions seem basic or do not make complete sense. I'm on the iOS learning path stage 1, with little OOP experience.
Question 1:
You are right about this. If you override the getter and setter then you need to #synthesize the property. I'll have to have a further look for why though.
Question 2:
Yes, you could just have the first method. However, the second method is there as a convenience and would normally contain code something like this...
- (void)addCard:(Card *)card
{
[self addCard:card atTop:YES];
}
Then the designated method would do something like...
- (void)addCard:(Card *)card atTop:(BOOL)atTop
{
if (atTop) {
// something to add card to top.
} else {
// something to add card at bottom.
}
}
i.e. it just routes the method call to the "designated" method but uses a default value for the BOOL.
Question 3:
The .h file is there as an interface file. It would be similar to a set of web services on a server. The class can do all sorts of stuff internally but it only needs to declare stuff in the .h interface file if something needs to access them externally.
For instance, you might have a class called Car. It might have a button called accelerator that would access an internal method and increase the speed. None of this needs to be exposed to external classes.
However, the same car might have a property called colour or a method called addFuel. These would need to be available externally so the user can see the colour and add fuel. These both need to go in the .h file.
I hope that makes sense.
Question 1: I have been taught I need to declare the synthesize when
overrides BOTH the getter and the setter. My question is: why only
when BOTH are being overriden? It should make more sense to me you
would need to declare the synthesize already when only one needs to be
overridden?
Once you use #synthesize you are using the setter/getter provided by the compiler. If you create your setter/getter without synthesize then you need to write both the methods, if you have readwrite property.
Question 2: Am I required to state these two as 2 individual methods.
Couldn't I just use the first one, whilst specifying 2 different
blocks of code to perform, by an IF ELSE clausule whether the BOOL is
YES or NO? Wouldn't that be exactly the same outcome?
Yes it is good to have two different methods. As these two vary on the parameters and the caller will know what is happening inside the method. If you wish to put if-else, for this you will require an ivar or a global value to check, but if you pass the BOOL no need for it.
Question 3: Having a rather simple program with just a single view, I noticed I do
not need to publicly specify any methods in my viewcontroller.h. I
reckon this only would be needed if your program is more complex and
contains several MVC where the controllers would need to "speak" to
each other. Is this a right assumption to make, generally speaking,
when making a proper MVC based program?
Even though you don't have any complex but always follow the architecture of MVC.
The controller in iOS programming usually refers to the view controllers. Think of a view controller as a bridge between the model and your views. This controller interprets what is happening on one side and uses that information to alter the other side as needed. For instance, if the user changes some field in a view, the controller makes sure the model changes in response. And if the model gets new data, the controller tells the view to reflect it.
Question 01
(edited) You need #synthesize to tell the compiler to create the ivar (eg. _myString) for you. You could also declare the ivar manually.
Question 02
You could just declare the first one yes. In fact the second one just a shorthand method, providing a default value for atTop. In most cases, you would implement the method exactly as you explained:
- (void)addCard:(Card *)card atTop:(BOOL)atTop {
if (atTop) {
// atTop == YES
}
else {
// atTop == NO
}
}
- (void)addCard:(Card *)card {
[self addCard:card atTop:YES]; // or atTop:NO, depending of the default value you want to use
}
Question 03
Again, yes. Your view controllers should expose as little properties and methods as possible, and make public only things that should be available for the rest of the application to use. So in the case of the single VC / single view program, having an empty VC interface is normal.

The best route to declare a BOOL as iVar or Property

I have read a few questions on the differences between iVars and Properties like these: Why would you use an ivar?
ios interface iVar vs Property
What I would like to know is... If I am creating a BOOL that needs to be accessed in multiple methods in a UIViewController (for example) what is the best way to create these?
At present I create proprties. This works fine and as expected. But as I read/learn more it appears that creating an iVar would be better for performance.
Like:
#interface ViewController : UIViewController{
BOOL myBool;
}
Would this be better for performance, and can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other - as I can with property approach?
can multiple methods access this iVar if I set the value to YES in one, can I check the value in the other
Of course you can, even if you set the value to NO. It is an instance variable and thus shared between all methods of one instance.
Would this be better for performance
No, unless you access the property very, very often, like 2^20 times per frame. Have a look at this Big Nerd Ranch post about iVar vs property performance. Usually the performance gain is not worth the loss in clarity.
The "better performance" is something that would be very rare to affect an app. Write code for clarity, then if there are performance issues profile and fix the code that is actually causing the problem.
For your purpose an ivar would be equivalent to using a property. Performance-wise the ivar is slightly better because you access it directly, whereas with a property you invoke a method (getter or setter) that was generated by the compiler in the background.
I wouldn't worry about performance, though. Typically the difference will be negligible. Unless you have some really special need, I would always use properties because it usually results in clearer code. It's also a good habit to have getter and setter methods - even if they are generated by the compiler for you - because they encapsulate the data of your class.
I usually go with this:
#interface MyVC : UIViewController
#property (nonatomic, getter=isDoingSomething) BOOL doingSomething;
#end
I also explicitly name the getter in the property declaration which gives you access to the property in a way that is easy to read. (Setting the property is done by sending setDoingSomething: and the getter is [theVC isDoingSomething])
Nonatomic properties are recommended on iOS. In regards to what I had backwards before, the default atomic behavior adds locks to the synthesized code, and is not recommended for performance reasons. Any issues with threads would have to be handled in your own setters (which you would have to do anyway when using an ivar). Personally I haven't ran into any issues with this.
I won't repeat other answers about performance but besides pointing out the fact that tapping a button sends way more messages than accessing a property, so the performance penalty is trivial.

IOS: When declaring properties in a .h what's the difference between self.var and just var? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C - When to use 'self'
I needed a variable to be passed from one view to another so I made a property called StringC in the .h and accessed it using self.StringC (that part worked).
I also need some arrays that are accessible throughout the view but I'm using them differently.
For instance I have lvLabelArray and I'm using
self.lvLabelArray=[[NSMutableArray alloc]init];
and then later I'm using
[lvLabelArray addObject:LabelText];
Is there a difference between that and
[self.lvLabelArray addObject:LabelText];
?
Sorry I don't know the terms for those kinds of variables.
There is an important difference there.
self.attribute goes through the object's getter or setter function, as appropriate. That allows you to set up initial values, trigger update messages, or anything else.
Accessing "attribute" directly goes straight to the underlying variable, so you bypass all that. As a result, it's definitely the less-preferable way of working.
A common way of avoiding this confusion, and just plain mistakes, is to rename the underlying variable. Instead of just "#synthesize attribute", use "#synthesize attribute = _attribute". This will create the getter and setter methods as before, but they'll the underlying variable is named "_attribute". That means that trying to use "attribute" without "self" will trigger a compiler error.

Resources