Swift / UIKit: understanding the structure of built-in methods - ios

I'm new to Swift and UIKit and, coming primarily from Python, I'm having trouble with the copy-paste-ness of tutorials and documentation I've been looking at thus far. I'm having a hard time getting a fundamental understanding of methods like:
override func tableView( ... numberOfRowsInSection ... )
override func tableView( ... cellForRowAt ... )
In practice I can use them without much issue, but I would appreciate any clarification or pointing to references that would explain:
Why are UIKit methods structured like this, rather than having a dedicated
func tableViewNumberOfRowsInSection( ... )
func tableViewCellForRowAt( ... )
(Or, why not have numberOfRowsInSection as an attribute of the subclass of UITableViewController, rather than one parameter of a function (tableView) that seems to have hundreds of uses?)
Function/Method basics such as labels, parameter names, etc make perfect sense to me, but I can't seem to make the jump to why func tableView would be structured the way it is.
What does the eventual call of tableView look like?
Thanks in advance for any help or pointers!

These are not the same function used in different ways — they are completely different functions, because the argument labels are part of the functions' names. The full name of each function is tableView(_:numberOfRowsInSection:) and tableView(_:cellForRowAt:) as you can see in the documentation. You might also want to read the Function Argument Labels and Parameter Names section of this guide, and maybe the naming guidelines.
You are unlikely to call these methods yourself, since they exist to provide data to the table view itself. UITableView will call your methods internally, which would look something like dataSource.tableView(self, cellForRowAt: indexPath). See the Delegation section in the Protocols guide for more on this pattern.
It's also worth noting that this API was created for Objective-C (before Swift was released), where their selectors are tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath:. That might be less confusing because the first argument label isn't "privileged" by being outside parentheses. That said, it's still considered a good design by Swift's naming standards, at least as long as the design needs to use classes (which it might not, if it didn't have to support Obj-C).

I won't go into too much detail in this answer, but it is true that delegate methods from UIKit (like the ones you show) tend to be long and near impossible to type out without help from auto-complete.
Nobody I know has memorized all of them (I've tried, and failed).
The reason being is somewhat legacy due to UIKit itself being written in Objective-C by Apple.
If UIKit were to be rewritten in Swift today (this will never happen due to the huge amount of effort Apple has invested into the framework over the years and the rise of SwiftUI), it's likely that the API would better follow practices for Swift API design.
To answer your questions specifically:
That's the way they've always been–if they were changed at all it would break a lot of developer's source code. Arguably the kind of method signatures you are proposing are not any better, just different. Also, if you read the full method signatures they do make sense and are clear enough.
Look into some tutorials for UITableView. The methods you are showing off come from UITableViewDelegate which is kind of the 'glue' you use to configure the table from your code. This is because back in the early Objective-C days the only way to do this sort of customisation was through this 'delegation pattern'.

Related

Is encapsulation in Swift as important as in other OO languages [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When I was learning other languages such as Java, all the sample code tells you that you should always mark a field private. And the methods that do the internal stuff are also marked private or protected.
But when it comes to Swift, I see that the sample code from a lot of the tutorials (such as raywenderlich.com) seldom marks something as private. They just leave it internal (without adding any modifiers).
In contrast, all the android tutorials mark some of the fields as private and provide no getters or setters for them.
For example, I read this search bar tutorial a while ago:
https://www.raywenderlich.com/113772/uisearchcontroller-tutorial
When I was reading through it, I was thinking about: "Why did you not mark this private?"
let searchController = UISearchController(searchResultsController: nil)
I mean, it does not make sense for other classes to access the search controller of my VC. It's mine!
Question:
Why don't most, if not all tutorials provide sample code that contains private properties? Is it because iOS is more secure or something? Should I mark suitable stuff as private in production code?
I hope this is not too opinion based. In Java, you will never make a field public, right? That's just a fact - you should not make fields public. So please don't close as opinion based, it's not.
Why not everything private? There are several really common scenarios that I've seen that always favor having the variable either internal or public.
Delegate methods:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(
myCellID,
forIndexPath: indexPath);
return cell;
}
This method will be called not internally by you, but rather by the iOS system that manages and displays the tableView. The delegation pattern is widely used within iOS development.
Data exchange between two ViewControllers, where you simply want to set the other ViewController's field:
class MyVC1: UIViewController {
var flagShouldUpateColors = false {
didSet{
// some stuff
}
}
}
Then at some point you want to notifiy this ViewController that the flag should be set to true. You do that my simply acccessing it's field.
Also selectors. When I register an instance of a ViewController for some notification, I pass the name of a method that I have within the very same ViewController. It is to be called when the notification triggers. Basically what the code says is "please call this method for me when this occurs". If you say call this private method when this occurs, it wouldn't make sense would it ? How is the caller supposed to call it(aside from reflection and other unoptimized ways). Here is example:
override func viewDidLoad() {
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(self.doStuffWhenEnterForeground),
name: UIApplicationWillEnterForegroundNotification,
object: app)
doStuffWhenEnterForeground();
}
func doStuffWhenEnterForeground() {
}
Main difference between Java and Swift is in properties.
Java has no concept of properties. It has fields and if you want to allow public access to those fields you can either access them directly or through getter/setter methods.
If you create public field that needs to be protected later on you will have to use methods and thus your public API will be changed - fields are accessed without parens and methods with them.
Swift is different in that regard. You can protect your field access with getter/setter at any point without changing API. So if you have field that is part of public API you can just leave it as is (without making it private) and without having getter/setter methods attached to it.
Encapsulation in Java and Swift are of the same importance. What differs is how it is achieved (implemented). Since there is no pressure for premature encapsulation in Swift and it is only matter of adding visibility specifier when appropriate there is some lack of discipline in adding those in tutorial code where main purpose is not enforcing encapsulation, but teaching some other concepts and how-to's.
Why don't most, if not all tutorials provide sample code that contains private properties? Is it because iOS is more secure or something? Should I mark suitable stuff as private in production code?
Probably because it's simpler, save few keystrokes and doesn't add unnecessary overhead to understanding the main theme of tutorial.
Should I mark suitable stuff as private in production code?
Yes, you should do it for the same reasons you would do it in Java. Notice 2 things, however:
There is no such thing as protected.
Access modifiers in Swift work differently compared to many other languages. private restricts access to variable or function to file where it was declared, regardless of who will access them. Thus, if you have 2 classes declared in the same file, they both can see private fields of each other. On the other hand, you can't see private fields even from extension of that class if this extension in other file. It looks strange at first and you just need to get used to it.

I need to understand why delegation in Objective-C is so important, what makes it so special?

So I've read about delegate explanation and practices a lot, but I still seem to not get it, I have specific questions and I would love to have some insightful simple answers.
Why use delegate over instance method? In UIAlertView why not just make – alertView:clickedButtonAtIndex: an instance method that will be called on my UIAlertView instance?
What is the delegate property? why do I have to make delegate property and define it with that weird syntax #property (nonatomic, strong) id <ClassesDelegate> delegate
Is delegate and protocol are two faces for a coin?
When do I know I should implement delegate in my app instead of direct calling?
Is delegate used as much and as important in Swift?
What gets called first and why? The method in the class who made himself a delegate? or the delegate method itself in class where it is declared?
Thank you for taking the time to go through this, I am desperately looking for a clear and helpful answers to my questions, feel free to give example or cover some related topic!
The advantage of delegation is Dependency Inversion.
Usually code has a compile-time dependency in the same direction of the run-time calling dependency. If this was the case the UITableview class would have a compile-time dependence on our code since it calls our code. By using delegation this is inverted, our code has a compile-time dependency on the UITableview class but the UITableview class calls our code at run-time.
There is a cost involved: we need to set the delegate and UITableview has to check at run-time that the delegate method is implemented.
Note: When I say UITableview I am including UITableviewDelegate and UITableviewDatasource.
See: Dependency inversion principle and Clean Code, Episode 13.
Maybe a real life example can better describe what's different in the delegation design pattern.
Suppose you open a new business, and you have an accountant to take care of the bureaucratic stuffs.
Scenario #1
You go to his office, and give him the information he needs:
the company name
the company # number/id
the number of employees
the email address
the street address
etc.
Then the accountant will store the data somewhere, and will probably tell you "don't forget to call me if there's any change".
Tomorrow you hire a new employee, but forget to notify your accountant. He will still use the original outdated data you provided him.
Scenario #2
Using the delegation pattern, you go to your accountant, and you provide him your phone number (the delegate), and nothing else.
Later, he'll call you, asking: what's the business name?
Later, he'll call you, asking: how many employees do you have?
Later, he'll call you, asking: what's your company address?
The day after you hire a new employee.
2 days later, he'll call you asking: how many employee do you have?
In the delegation model (scenario #2), you see that your accountant will always have on demand up-to-date data, because he will call you every time he needs data. That's what "don't call me, I'll call you" means when talking of inversion of control (from the accountant perspective).
Transposing that in development, for example to populate a table you have 2 options:
instantiate a table control, pass all the data (list of items to display), then ask the table to render itself
instantiate a table control, give it a pointer to a delegate, and let it call the delegate when it needs to know:
the number of rows in the table
the data to display on row no. n
the height the row no. n should have
etc.
but also when:
the row no. n has been tapped
the header has been tapped
etc.
Firstly, don't feel bad that all if stuff isn't clear yet. This is a good example of something that seems tricky at first, but just takes time really click. That will happen before you know it :-). I'll try and answer each of your points above:
1) Think of it this way - the way UIAlertView works now, it allows Apple to “delegate” the implementation of the alertView:clickedButtonAtIndex: to you. If this was an instance method of UIAlertView, it would be the same implementation for everyone. To customize the implementation would then require subclassing - an often over relied upon design pattern. Apple tends to go with composition over inheritance in their frameworks and this is an example of that. You can read more on that concept here: http://en.wikipedia.org/wiki/Composition_over_inheritance
2) The delegate property is a reference to the object which implements the delegation methods and whichs should be used to “delegate” those tasks to. The weird syntax just means this - a property that holds a reference to an object that adheres to the protocol.
3) Not quite - delegation leverages protocols as a means for it’s implementation. In the example above, the is this the name of a protocol that an object which can be considered a delegate for that class must adhere to. It is inside that protocol that the methods for which a delegate of that class must implement are defined. You can also have optional protocol methods but that’s a different topic.
4) If I understand the question correctly, I think a good sign that you may want a delegate to be implemented instead of simply adding instance methods to your object is when you think that you may want the implementation of those methods to be easily swapped out or changed. When the implementation of those methods changes considerably based on where/how the functionality your building is being used
5) Absolutely! Objective-C and Swift are programming languages and the delegation pattern is an example of a design pattern. In general design patterns are hoziontal concepts that transcend across the verticals of programming languages.
6) I’m not sure I understand you exactly but I think there’s a bit of misunderstanding in the question - the method does not get called twice. The method declared in the delegate protocol is called once - typically from the class that contains the delegate property. The class calls the delegates implementation of that property via something like:
[self.delegate someMethodThatMyDelegateImplemented];
I hope some of this helped!
Sometimes you want your UIAlertView to work different in different contexts. If you set your custom UIAlertView to be delegate of itself it has to provide all those contexts (a lot of if/else statements). You can also set seperate delegate for each context.
This way you say to your compiler that every class (id) which implements protocol ClassesDelegate can be set to this property. As a side note it should usually be weak instead of strong to not introduce reference cycle (class A holds B, and B holds A)
Protocol (interface in other languages) is used to define set of methods which should be implemented by class. If class conforms to the protocol you can call this methods without knowledge of the specific class. Delegate is pattern in which class A delegates some work to class B (e.g. abstract printer delegates his work real printer)
When you need few different behaviours which depends on context (e.g. ContactsViewController needs to refresh his list when download is finished, but SingleContactViewController needs to reload image, labels etc.)
It is one of the most fundamental patterns in programming, so yes.
It's the same method
You can't just add a method to UIAlertView, because you don't have the source code. You'd have to subclass UIAlertView. But since you have more than one use of UIAlertView, You'd need several subclasses. That's very inconvenient.
Now let's say you use a library that subclasses UIAlertView, giving more functionality. That's trouble, because now you need to subclass this subclass instead of UIAlertView.
Now let's say that library uses different subclasses of UIAlertview, depending on whether you run on iOS 7 or 8, and UIAlertview unchanged on iOS 6. You're in trouble. Your subclassing pattern breaks down.
Instead, you create a delegate doing all the things specific to one UIAlertview. That delegate will work with the library just fine. Instead of subclassing a huge and complicated class, you write a very simple class. Most likely the code using the UIAlertview knows exactly what the delegate should be doing, so you can keep that code together.

Why do we needed category when we can use a subclass? and Why we needed blocks when we can use functions?

These two questions are quite common when we search it but yet I need to get a satisfying answer about both.When ever we search a difference between say subclass and a category we actually get definition of both not the difference.I went to an interview to a very good MNC working on iOS and I was encountered with these two questions and I gave almost all the answers I have read here but the interviewer was not satisfied.He stuck to his questions and was that-
Why do we needed category when we can use a subclass?
Why we needed blocks when we can use functions?
So please explain me what specific qualities blocks and category add in objective C that their counter part can't do.
First...
Just reading the documentation "Subclassing Notes" for NSString shows why creating categories is sometimes better than subclassing.
If you wanted to add a function -(void)reverseString (for instance) to NSString then subclassing it is going to be a massive pain in comparison to categories.
Second...
Blocks are useful for capturing scope and context. They can also be passed around. So you can pass a block into an asynchronous call which then may be passed elsewhere. TBH you don't care where the block is passed or where it is finally called from. The scope captured at the time of creating the block is captured too.
Yes, you can use methods too. But they both have different uses.
Your questions are a bit odd. It's like asking...
Why do hammers exist when we can just use wrenches?
You can't use subclassing when someone else is creating the objects. For instance, NSString is returned from hundreds of system APIs, and you can't change them to return MyImprovedString.
Functions split up the logic; blocks allow you to write it closer together. Like:
[thing doSomethingAndWhenFinishedDo: ^{ some_other_thing; }];
the same code written with functions would put the second part of the logic several lines away in the file. If you have a few nested scopes in your logic then blocks can really clean it up.
Why do we needed category when we can use a subclass?
Categories let you expand the API of existing classes without changing their type. Subclassing does the same thing but introduces a new type. Additionally subclassing lets you add state.
Why we needed blocks when we can use functions?
Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.
You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution
Category : It is used if we want to add any method on a given class whose source is not known. This is basically used when we want to alter the behaviour of any Class.
For example : If we want to add a method on NSString to reverse a string we can go for categories.
Subclassing : If we want to modify state as well as behaviour of any class or override any methods to alter the behaviour of the parent class then we go for subclassing.
For example : We subclass UIView to alter its state and behaviour in our iOS code.
Reference :
When to use categories and when to use subclassing?
What is the difference between inheritance and Categories in Objective-C
We need new method but we don't need new class so we need category.
We need function but we don't need named function so we need block.

How should we document the delegate methods in iOS using Doxygen?

Using Doxygen i have documented the methods declared by me and could generate documentation.
but i am looking for documenting the view life cycle methods and even delegate methods.
Can any one help me in achieving my requirement. All i am looking for is the equivalent documentation in doxygen as { #inherited } in javaDoc
Take a look at this It will give you an idea for what syntax to use for objective-c.
Edit: For docs on the View lifecycle, you would need to decide if you are doing anything outside of the ordinary that justifies needing comments(are you doing more than just updating data on viewwillappear).If you are can the code in those sections be broken out into another method (and then commented on the same as a normal method which would be my suggestion).
Hope this helps.

Difference between objectAtIndexedSubscript and objectAtIndex

I have searched quite bit on stackoverflow and other resources, can't find an answer.
What is the difference between the NSArray methods objectAtIndexedSubscript and objectAtIndex?
Or, if there is no difference, why do both exist?
In the Apple Docs it says they are "identical".
I am super new to programming but if they are identical, isn't that breaking the DRY principle? Obviously the guys at Apple know what they are doing, but why are they both provided if they are identical? Or maybe a better question is, why should I use one over the other?
They are identical.
-objectAtIndex: is the method you should use.
-objectAtIndexedSubscript: is the method that provides support for obj-c subscripts. In other words, this method is what the compiler uses if you say array[3]. But for NSArray* it does the exact same thing as -objectAtIndex:. The reason why it's a different method is so other classes can implement this in order to support obj-c subscripts without having to use the generically-named -objectAtIndex:.

Resources