Is all overridable methods are lifecycle methods - ios

My concern is the following,
If I create a Class with some method and inherit it then which methods are called lifecycle methods.
Are all overridable methods lifecycle methods? And in which category does it fall e.g OOPS ,OOAD
Example:- In iOS viewDidLoad is a lifecycle method but didReceiveMemoryWarning is not.
If it is not called a lifecycle method , is it called a overridable method?

Methods don't have type like life cycle method or overridable method etc.
UIViewController have it's own life cycle as per it's behavior that it is load or it appear etc.
And overriding is concept of inheritance. So there is no standard type like life cycle or overridable. Methods which are called from initialization of viewController to Disappearance, comes under lifecycle of viewcontroller.

We use override when we want to add some features to our method from super class.
If you create a class and implement UIViewcontroller as superclass.UIViewController has predefine method such as viewDidload, viewWillAppear,viewDidDisapear and others. If you want to add some features to superclass methods you should use override prefix. Override is used when you implement method of superclass and add your code.
For example
class Student{
func address(){
var add1 = "drn"
}
func phoneNumber(){
var no = 9806569690
}
}
//create another class and add student as superclass
class Classroom: Student{
//here address is method from superclass student so i am using override prefix
override func address(){
var add2 = "ktm"
}
}
Actuctually i am typing from mobile phone. So i could not give you good example.

Related

Providing a default implementation for an overriden UIViewController method, but only if the controller conforms to a protocol

In my app I've had a lot of boilerplate code I had to write whenever there was a UITableView in some controller. To eliminate it, I created a BaseTableViewController that implements some repeatedly used UITableDataSource operations like tableView(_:numberOfRowsInSection:) and tableView(_:cellForRowAt:). In tableView(_:numberOfRowsInSection:), my BaseTableViewController retrieves the actual number of rows in a section from another method (let's call it rowCount(inSection:)) and performs some computations using it, then returns the result to the delegating caller. Each class subclassing the BaseTableViewController must override the rowCount(inSection:) method and return its proper row count in a given section (BaseTableViewController itself returns 0 in its default implementation).
Now, some of my table view controllers support paging for displayed records - when the users scrolls the table view to its last row, next batch of rows is retrieved from the network. Trying to make things more protocol-oriented, I created a protocol for pageable controllers:
protocol Pageable: class {
associatedtype DataType
var pages: [[DataType]] { get set } // Each page is an array of elements, hence the table in a table
func loadNextPage()
}
If a controller is Pageable, the rowCount(inSection:) methods always looks like this:
override func rowCount(inSection: Int) -> Int {
return self.pages[section].count
}
This is tedious, because every BaseTableViewController descendant that is also Pageable must have this exact implementation, which violates DRY.
I cannot add a default implementation in a protocol extension for Pageable, because the controller already has its own implementation inherited from BaseTableViewController.
I came up with a solution, but I don't like it: I could create a PageableTableViewController (a subclass of BaseTableViewController) that provides its own overriden implementation of rowCount(inSection:), but that's not very protocol-oriented. I also tried to move the rowCount(inSection:) method to a protocol, but if I make all descendants of BaseTableViewController to conform to that protocol with a protocol extension, extending Pageable to implement the method won't work.
How would I create a mechanism where all subclasses of BaseTableViewController would be able to override the rowCount(inSection:) method, but when they're Pageable, they share a default implementation of it that's (possibly) placed in a Pageable protocol extension?
You can achieve what you are looking for with protocol extensions. the extension will apply just in case the object implementing the protocol is actually an UIViewController.
protocol something {
func method()
}
extension something where Self: UIViewController {
func method() {
//Default implementation
}
}

Override function

I am taking a iOS course online provided by a famous university. I don't understand why the following code use override and it is legal.
According to the official definition, we use override to override superclass' methods. Where is the subclass and superclass in the following code?
What's been override and by what?
public override var description: String {
return "\(url.absoluteString) (aspect ratio = \(aspectRatio))"
}
Here is an example:
Your original class:
class Person {
func walk() {
//do something
}
}
Your subclass:
class Runner: Person {
override func walk() {
//do something that is different from Person's walk
}
}
In the Runner class, there is an override with the function walk. That is because it is a subclass of Person, and it can override Person's walk function. So If you instantiate a Runner:
var usainBolt = Runner()
And you call the walk function:
usainBolt.walk()
Then that will call the overriden function that you wrote in the Runner class. If you don't override it, it will call the walk function that you wrote in Person.
According to the official definition, we use override to override superclass' methods.
That's correct. The superclass in your example is the class that encloses the override of description property. This could be NSObject, some other class derived from it (directly or indirectly), or some class unrelated to NSObject that has var description: String property.
description is a property that Swift classes commonly have as a way to present themselves as a string, because description provides conformance to CustomStringConvertible protocol. This is similar to toString() method of Java, and to str() method of Python.
What's been override and by what?
The implementation of the property is what's being overridden. The class that has the implementation does the overriding.

Protocol Oriented Programming, implicitly calling extension method

Having my first crack at POP. In this case I want to decorate some UIViewControllers so that any that they automatically raise a 'Page viewed' analytics event.
So I created a protocol, and and extension for that protocol:
protocol ReportPageViewedEvent {
func reportPageViewed()
var pageName : String? { get set }
}
extension ReportPageViewedEvent where Self: UIViewController
{
func reportPageViewed()
{
guard let pageName = self.pageName else
{
fatalError("UIViewController implements ReportPageViewEvent protocol but did not set pageName property")
}
let eventBusiness = EventBusiness.sharedInstance
eventBusiness.logUserViewedPage(pageName)
}
}
This works as I want, if I decorate a UIViewController with ReportPageViewedEvent like this:
class HomeView: UIViewController, ReportPageViewedEvent {
I get a compiler error unless I set 'pageName' which is exactly what I want.
Where I am getting unstuck is where and how to call the actual reportPageViewed() method. I really want it to be called from viewDidLoad which means I either have to modify every 'viewDidLoad' in every controller that uses it, or subclass and call the method in the super class which defies the point of using POP in the first place.
Is there a nice way to achieve this. I can't find an example like this in any tutorial/blog.
Basically, there is always some behaviour shared by all the screens of your app. So it is appropriate to create a class called (for example) BaseViewController so all the other view controllers will inherit from it.
In BaseViewController's viewDidLoad you can call the reportPageViewed() method.
However, this approach makes the Protocol Oriented Programming not needed. Protocols are useful when you need to assign some same behaviour to objects that have nothing in common (which is not the case for app screens).

instance methods from class methods swift

I have a class TestClass and a class & instance method inside it
class TestClass {
class func classMethod(){
print("how do i call instance method from here")
}
func instanceMethod(){
print("call this instance method")
}
}
My question is how do i call that instanceMethod from classMethod??
One way i have noticed is
class func classMethod(){
TestClass().instanceMethod()
}
But,Is this the good way to do?
What you are trying to do rarely makes any sense from a design perspective.
By definition, an instance method operates on an instance of an object.
For example, it might require access to some instance members, or somehow meddle with the state of the object you call the method on.
class methods on the other hand do not require an instance to be able to call them - and should in general only operate on the given parameters, not be dependant on shared state.
If you need to call instanceMethod() in classMethod(), and instanceMethod() does not require any state - why is it not also a class method, or a (global) pure function?
You can pass the instance object as a parameter to the class method, and then call the instance method of the object:
class TestClass {
class func classMethod(obj:TestClass){
print("how do i call instance method from here")
obj.instanceMethod()
}
func instanceMethod(){
print("call this instance method")
}
}
To call the instance method, you need an instance of TestClass. That's what TestClass() is getting you when you call TestClass().instanceMethod().
If you want to call it from a specific instance, you could pass it in as a parameter to the class function: class func classMethodUsingInstance(instance: TestClass)
If you don't need a specific instance for instanceMethod(), maybe consider making it a class method as well.

Swift class with only class methods and a delegate?

I want a class with all class methods. I would like to use a delegate so my view controllers (conforming to the protocol) can call AlertFactory.passwordResetSucess() and display the alert.
Is there a way to make this this work? A way to use the delegate from this class?
Is this bad practice? Bad form? Why?
What's a good way to make this happen? There will be other class methods used in several views.
Thanks!
protocol AlertFactoryDelegate
{
func showAlert(alert: UIAlertController)
}
class AlertFactory: NSObject {
let delegate: AlertFactoryDelegate!
class func passwordResetSuccess()
{
var alert = UIAlertController(title: "Success!", message: "Yay", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Continue", style: UIAlertActionStyle.Default, handler: nil))
delegate.showAlert(alert)
}
}
You can set delegate to be static, and access it with AlertFactory.delegate
class AlertFactory: NSObject {
static weak var delegate: AlertFactoryDelegate?
class func passwordResetSuccess() {
...
self.delegate?.showAlert(alert)
}
}
To create a delegate:
class SomeClass: AlertFactoryDelegate {
... // Implement everything the protocol requires
}
// Asssing a delegate
AlertFactory.delegate = SomeClass()
You cannot set an instance variable on a class without instantiating the class first. Is there a reason you don't want to instantiate the class, and just want to use class methods instead? If you feel that you have good reason to use class methods over instance methods, then you have two potential options:
Pass a delegate as a parameter to the class method.
Use Completion Blocks instead of Delegation. Here's a decent example in swift.
In my personal experience I find blocks to be preferable.
EDIT: I haven't used Swift that much lately, but as #Skrundz pointed out you can indeed use a static variable on a class in Swift.
You could use the SINGLETON command pattern, its a very common practice. You should read up on it, but basically means there is only 1 ever instance of it and you can call methods off of it when needed (or send things to it as needed). Common examples are EventSystem objects or GlobalObserver objects, Factories, and ContextManagers.
Here is information on it:
https://sourcemaking.com/design_patterns/singleton
Using a SINGLETON has tradeoffs, but can be very useful in many situations. This seems like a good pattern for your problem.
You need to initialize your delegate when your app starts. From then on, when another view controller needs to set that delegate you can assign it: (this assumes you made delegate public and its a SINGLETON)
_myViewController.actionThatRequiresDelegate = AlertFactory.delegate
As mentioned in one of the other answers, using Swifts trailing syntax closure system is a great way to use anonymous functions and you could do your logic in there, or communicate with your delegate in there.
update
Initialize in the AppDelegate.swift:
override init()
{
AlertFactory.init()
}
Then in your AlertFactory
public static AlertFactoryDelegate myDelegate
public static func init()
{
myDelegate = new AlertFactoryDelegate()
}

Resources