Swift Code Snippets | Save Developer Hours

Do you write hundreds lines of code everyday ? And would you like to save ? Well than, code snippet libray may help you here.

The Concept of code snippets is saving a piece of code which we write very often. so now we can save it as snippet and use it quickly with shortcuts or drag & drop.

Here it is in IDE.

Screen Shot 2017-05-30 at 9.11.33 PM.png

How to build A Custom Snippet ?

By default, Xcode provides serval snippets and let add our own.

  1. Select the code which you want to create as snippet.
  2. Just drag and drop inside the Snippet option.

ima.png

we can also Edit Custom Snippet, Give the title and summary to our snippet, Completion Shortcut is what i like most its just give short name, define the scope, if its no longer required just select and delete it.

 

 

 

Objective C Days | Memory Management |Short Note to Brush up

Summary

Let’s see the traditional C ways for clearing up of unused objects is a bit of a nightmare. There are no ways in the language like how should be approached.

Imagine one function A create one object and pass it to another function B now both are using the same data now the problem is who is: the responsible for deleting it if it no longer used? and let’s say we have one function who is also gonna use the same data than what?

The solution is there are conventions and design patterns to handle these situations,  that’s the reason the reference counting was developed and management technique used in Obj-C.

What we have in Obj-C

Obj-C uses reference counting as its Memory Management Technique so according to that each object keeps an internal count of how many times it’s needed.  So only in case of, if count drops to zero. Yes you can compare it with Garbage Collector we have in Java but it’s not like automatic some chunk of code getting executed and removing the objects which ones are not needed.

Ownership

Most important thing is Object Ownership it means an object owner is someone that has explicitly said: “I need that object, don’t delete”. So one object can have more than one owner.

If object owner is not using it they have the responsibility to tell so that the reference count should be decreased by one. So while dealing with Obj-C pointers/Objects it’s really good to send correct messages.

Messages

alloc, it will allocate a fresh instance of the object, set the reference count +1.

new, shortest way to write alloc&init.

retain, you passed the object and you want to tell you to need that so its reference count should be increased by 1 again.

autorelease, need object temporarily and want to delete once you did with the operations.

copy creates a new copy of the object.

dealloc, opposite of init method, automatically get called right before the object is destroyed.

 Convenience Methods

Static methods used for allocating the initializing objects directly but are aware that you are not the owner of that object, once the scope of your program finish it will be removed.  Ex: [NSString stringWithFormat:@”Say %@”,@”Hello”];

Autorelease Pools

It’s an instance of NSAutoreleasePool, objects which are to be auto released. You can also send a message to autorelease or create object using convenience methods. So once the object added into autorelease pool and when the pool is popped, all the objects will be deleted.

Retain Cycles

Retain cycle is a condition where two objects strongly maintain a reference to each other and stop each other from being released. For example, let we have two classes as.

@interface Parent : NSObject
@property (nonatomic, strong) Child *child;
@end

@implementation Parent
@end

@interface Child : NSObject
@property (nonatomic, strong) Parent * parent;
@end

@implementation Child
@end

So, at some point of time when creating object of any of these class as

Parent *parent = [[Parent alloc] init];
Child *child = [[Child alloc] init];
parent.child = child;
child.parent = parent;

Here the parent object maintaining a strong reference of Child class and child object maintaining a strong reference of Parent class in back. So, both parent and child object having a reference count of one and one. Both objects will get released from memory only when their reference count will reach to zero but in this scenario, this will not be going to happen ever because both are mutually pointing to each other a dead lock is get created here. This situation is called the Retain Cycle that will lead to memory leaks.

Fortunately, it’s very easy to fix this problem—just tell one of the properties to maintain a weak reference to the other object so, what’s this weak and strong reference means??

Strong Reference: A strong reference says that don’t release this object till I m owning this.

Weak Reference: A weak reference says that don’t release this object until someone else pointing this strongly.

Just like strong and __strong, weak and __weak keywords are there for declaring properties and instance variables respectively as a weakly referenced object.

Quick Tips and common mistakes

Think about strong and weak pointers as well as retain cycles, Avoid unnecessary caching, Don’t declare every object  globally unnecessarily, use Xcode Instruments such as static analyzer and find the potential memory leaks and fix them

Arrays, Dictionaries and other objects that contain any object generally retain objects once you add it to them. It means once you create an object the reference count will be 1 and once you add it into an Arrays it will be 2.

Releasing the Object that you don’t own, let’s say if creating a new object using convenience method than there is no need to release that.

Keeping and using an Object that you don’t Own.

Calling dealloc directly. So never call dealloc by the way you have to call init after calling alloc its kinda default constructor for init the default value of the object.

Over-releasing. Accidentally you’re releasing something twice instead of once. You can also track these crashes by just enabling Zombies.

Retain Cycles. When an object released there is a cascading effect, the root object released its children’s as well and so on. Let’s say there is some condition like A owns B and B owns An as they own each other.

iOS Concurrency | Introduction | Options

Concurrency is two sided-weapon, that you should master and learn how to use because it will help you to write efficient code with fast execution but if you are misusing it, then results will be poor app performance, crashes etc.

So before writing code think about the problem, why do we need that and which API do you need to resolve it.

In iOS, we have different APIs that we can be used. But wait here the question is why do we need Concurrency?

  • Utilize iOS Hardware: Now all of the iOS devices are with multi-core processors that allow developers to execute multiple tasks parallel. So here we can earn lots of benefits.
  • Better User Experience: Code for call multiple web services, handle IO and some heavy tasks etc will freeze UI and make your app nonresponsive so if as a user I face this I will close the app for sure, but with concurrency, all tasks can be done in the background without hanging the main thread.
  • APIs like NSOperation and Dispatch Queues makes it really easy: Earlier creating and managing threads is not easy that’s the reason everyone gets scared when they hear about concurrency. Another major advantage of APIs is, it will also help you to manage synchronization to avoid the race condition, it happens with two threads try to access the shared resource.

Properties | Swift | iOS | Stored

Properties associate value with a paticular class, structure or enumeration. Stored Properties (provided by class, struct and enum) store constant and variable values as part of instance, whereas Computed Properties (provided by class and struct only) calculate a value. Properties can also be associated with type itself its called Type Properties. Apart from that we can add observers to monitor the changes in a property’s value there you can response to your custom actions, we can add it to Stored Properties and also property that a subclass.

Stored Properties

Simplest form, its a constant or variable that is stored as a part of an instance of a particuler class, struct or enum.

struct Box  {
    var height  : Int
    let width   : Int
}

var box1 = Box(height: 101, width: 10)

It can be either Variable stored property (introduced by var) or Constant stored property(introduced by let). if its Variable stored property than we can set initial value during initialization and if Constant stored property without default value than yes as well.

Lazy Stored Properties

Whose initial values is not calculated until the first time it is used. they are useful when the initial value for a property is dependent on other factors or sometime if the initial value for a property requires complex or computationally expensive setup that should not be performed unless it is needed.

class DataImporter  {
    /*
     This class is responsible for fetching and holding the file data.
    */
    var fileName = "data.json"
}

class DataManager   {
    var data = [String]()
    lazy var importer = DataImporter()
}

let dManager = DataManager()
dManager.data.append("One")
dManager.data.append("two")

Now here the interseting part is till now importer property is not created. because is marked as lazy so the property is only created when the importer property is first accessed.

 

Subscripts in Swift ?

Shortest way to access the member elements of collection, list or sequence, means there is no need to create saparate function. lets say you have an array so you can write subscripts for setting and retrieving the value by index. Sounds good ???

Another good thing is we can define number of subscripts based on the type of index value we pass, even we can define subscripts with multiple input parameters, so its all to our need.

The syntax is very much similar to stored property and functions. Just we need to write subscript keyword and specify one or more input paramters and reture type. like the methods subscripts are also read-write or readonly. This behaviour is communicated by the same way we do in computed properties. 

subscript(index: Int) -> Int    {
    get {
        //return value here
    } set(newValue) {
        //set the new value here
    }
}

the usage is to access the member elements in a collection, list or sequence. For example, Swift’s Dictionary instance. You can set and get the value using Key. if they key does’t exist it will add into the Dictionary.

var priorities = ["Work" : 3, "Family" : 1, "Other" : 4]
priorities["Work"] = 2

Swift’s Dictionary type implements its key-value subscripting, its takes and returns an optional value. if you set the value as nil it’ll remove from Dictionary.

priorities["Work"] = nil

the interseting part what i like is subscripts can take any types of values, n number of value and can return any type of value, but they can’t use in-out parameters and can’t provide default parameters value.

struct Matrix {
    let rows: Int, columns : Int
    var grid : [Double]

    init(rows: Int, columns: Int) {
        self.rows = rows
        self.columns = columns
        grid = Array(repeating: 0.0, count: rows * columns)
    }

    private func isValidIndex(row: Int, column: Int) -> Bool    {
        return row >= 0 && row < rows && column >= 0 && column < columns
    }  

    subscript (row: Int, column: Int) -> Double  {
        get {
            assert(isValidIndex(row: row, column: column))
            return grid[(row * column) + column]
        } set {
            assert(isValidIndex(row: row, column: column))
            grid[(row * column) + column] = newValue
        }
    }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[1, 1] = 10.0

print(matrix[1, 1])

Top 10 reasons for iOS app rejection ?

Today apps are changing the world. The App Store has grown into an exciting and vibrant ecosystem for millions of developers. Whether you are a first-time developer or a large team of experienced programmers, we are excited that you are creating apps for the App Store and want to help you understand our guidelines so you can be confident your app will get through the review process quickly.

Here are top 10 reasons for app rejections from Apple.

16% Guideline 2.1 – Performance: App Completeness

14% More Information Needed

9% Guideline 4.1 – Design: Copycats

8% Guideline 2.3.7 – Performance: Accurate Metadata

4% Guideline 3.1.1 – Business: In-App Purchase

4% Guideline 2.3.3 – Performance: Accurate Metadata

3% Guideline 4.0 – Design: Spam

3% Guideline 4.0 – Design

3% Guideline 2.3.3 – Performance: Accurate Metadata

3% Did Not Comply with Program License Agreement

Failable Numeric Conversion Initializers | Swift 3.1

Swift 3.1 implements failable initializers for all numeric types like Int, Int8, Int16, Int32, UInt, UInt8, UInt16, UInt32, Float, Float80, Double. So which either completely successful without loss of information or simply returns nil.

This feature is very useful let’s see an example.

typealias JSONDictionary = [String: AnyObject]
class Employee  {
    let name: String
    let level: Double
    init?(json: JSONDictionary) {
       guard   let name = json["name"] as? String,
           let levelString = json["level"] as? String,
            let levelDouble = Double(levelString),
            let level = Int(exactly: levelDouble)  // 3.1 feature here
            else {
                return nil
        }
        self.name = name
        self.level = level
    }
}

func getEmployees(from data: Data) -> [Employee]?   {
    guard let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
        let jsonArray = json as? [JSONDictionary]   else {
            return nil
    }

    return jsonArray.flatMap(Employee.init)
}

let jsonString = "[{\"name\":\"John\", \"level\":\"7.2\"}]"
if let data = jsonString.data(using: .utf8) {
    let employees = getEmployees(from: data)
    print(employees ?? "its Nil")
} else {
    print("Data Nil")
}

@IBInspectable & @IBDesignable

IBInspectable – provided new ways to old features like user defined runtime attribute are powerful way to configuring any Key-value coded property of an instance XIB. But its really hard to manage and if you have multiple views with same or may be different properties.

for example, these properties in UIView subclass update the backing layer with their values.

@IBInspectable var corberRadius : CGFloat = 0 {
        didSet {
            layer.cornerRadius = corberRadius
            layer.masksToBounds = corberRadius > 0
        }
    }

IBDesignable lets interface builder know it should render the view directly in the canvas. This will allow you to see how’s your view will appear without even building the application.

@IBDesignable
class BaseView: UIView {
    @IBInspectable var corberRadius : CGFloat = 0 {
        didSet {
            layer.cornerRadius = corberRadius
            layer.masksToBounds = corberRadius > 0
        }
    }
}

Moreover any problems can be debugged without even compelling and running the whole project, how ? Just choose, Editor and Debug selected views.

whenever we are compiling the code prepareForInterfaceBuilder and there we can make required check either the target is interface builder or else.

nullable ? Swift – Objective C

Did you ever think? what will happen if your Objective C function will return nil to Swift function? because there is optional in Swift for managing nil values but in Objective C nothing.

//Objective-C code 
#import <Foundation/Foundation.h> 
@interface ObjCHello : NSObject 
-(NSArray * )getValue; 
@end  

//Swift code 
let objc = ObjCHello() 
print(objc.getValue()) 

//Objective-C 
#import <Foundation/Foundation.h> 
@interface ObjCHello : NSObject 
-(NSArray * _Nullable)getValue; 
@end

Now it will return value [Any]? and it won’t crash so just go for optional chaining.

MVC vs MVVM

Ever heard of MVC?

Yes, its massive view controller 🙂 some call it and its true, because a lot of logic get placed in the view controller only. so today we are trying to convert it into MVVM, yes its Model-View-ViewModel.

first of all here is typical setup of MVC.

MVC.png

Model represent data, views represent user interface and view controller mediate the interaction between two of them.

So there thing about that view and view controller are typically distinct components and they almost go together – tightly coupled. but a view could be paired with different view controllers or vice-versa. so why not formalise their connection.

MVC1.png

There are few things that we only need in view controller like presentation logic.  so make it more clear lets add it into flow.

MVVM.png

i know its looking much better now. its an argumented version of MVC where we move presentation logic out of the controller into a new object – the view model. The motivation behind that is reduce the complexity of view controller.