Monday, July 17, 2017

What’s New in Swift

This article is just a short overview of this WWDC session.


Here are the few things that were discussed as part of the session:


1.) Private variables are now accessible to all the extensions of the class in the same file.


2.) Composing a class with any number of protocols.

Example : 
protocol Shakeable {
    func shake()
}
extension UIButtonShakeable {}
extension UISliderShakeable {}
func shakeControls(controls: [UIControl & Shakeable]) {
    for control in controls where control.state.isEnabled {
        control.shake()
    }
}

3.) Swift Versions:

Swift 4 is source-compatible with Swift3.
Swift3.2 introduced that contains most of the Swift4 syntax changes.
So, there will be 2 Swift versions in Xcode9: Swift3.2  & Swift4.

The end result is: If you open a Swift 3 project in Xcode9 and build the project with Swift3.2, it should work as it is, i.e., without any code changes.
This is mainly to give the developers time to adopt to the new Swift changes, so that the project dependencies can migrate asynchronously.

4.) New faster Build system:

Includes these:
(i) The pre-compiled header is the default option for compatibility between Obj-C & Swift classes.
The Bridging headers are build each time when a build is run, whereas the Xcode9’s default ‘Pre-Compiled header’ is build only once, which improves the build time for projects that contains huge amount of Legacy Objective-C classes.

(ii) Code Coverage: Xcode8 runs a separate build, where Xcode 9 will use the same last build when you run a test with Code Coverage, which eventually reduces the test execution time.

(iii) Indexing is not a separate background process now, it is done along with the build process that has a small overhead to the build, of course.

(iv) No unused code is build, the compiler just omits it. (It doesn’t mean that we should have unused code in our projects ;) )


5.) Strings:
(i) String collections can be directly manipulated without using the internal ‘characters’ collection.

Example:
let values = "one, two, three…"

//To get index after the ‘,’ char from the ‘values’ string
Swift 3:
while let comma = values[i..<values.endIndex].index(of: ",") {
    let index = values.index(after: comma)
}

Swift4:
while let comma = values[i..<values.endIndex].index(of: ",") {
    let index1 = values.characters.index(after: comma)
}

(ii) String ‘characters’ collection iteration can be iterated without using ‘values.endIndex’ in the below example.

Swift 3:
var i = values.startIndex
while let comma = values[i..<values.endIndex].index(of: ",") {
}

Swift 4:
var i = values.startIndex
while let comma = values[i...].index(of: ",") {
}

(iii) Substring cannot be used as it is from Swift 4. It needs to be copied before using it further, this is to overcome an issue of memory leak with Substring before Swift4.

Example:
let big = downloadHugeString()
let small = extractTinyString(from: big)

Swift 3:

myLabel.text = small // This leads to the memory leak, since the 'big' text is being holded by the internal String classes that does the process of extracting the substring from the given 'big' string.
Swift 4:

myLabel.text = String(small)//Hence, this is the recommended/only way to use the substring going forward.
This mainly affects huge string operation. Doesn’t majorly have any great effect on the small string manipulations.



(iv) Multi line strings literals are easier to write now.

Swift 3:

let longString = "Q1: Why does \(name) have \(n\(characters)'s in their name?\nA: I don't know.Q2: H r u?\nA: I am \(name)"
Swift 4:
let longString = """
                Q1: Why does \(name) have \(n) \(characters)'s in their name?
                A: I don't know.
                Q2: H r u?
                A: I am \(name)
                """

Saturday, June 24, 2017

My MOOC course on FRP

Hey Guys,

Recently the  Functional Reactive Programming(FRP) is getting a lot of traction, hence i started doing it and ended up getting addicted to it so much that Now i’m unable to go back and do the imperative programming at all.

So i ended up creating a MOOC course on it, because i saw none of the course on this topic at all.
Also, i’ve made sure to cover the best practices (Like VIPER, TDD, POP) followed in the industry to have an added bonus for those who enrol into this course.
I’m pretty sure that it will help many people to adopt this awe-somatic way of writing the code.

Here’s the link to my course. 
For those who prefer to enrol, i can provide offer codes to take it up for a better/lesser price.
I would basically like to trade it off for a rating/review on Udemy’s course page.

I hope that you’d also share it with your friends and everyone around. Please get the word out. Even if they’re new to iOS programming, i’m pretty sure that it will help them grasp the knowledge on FRP, which i think is the future of programming.

Critics are very welcome!

Thank you for your valuable time!

See you! Bye, until next time! Have Fun!

Thursday, June 8, 2017

WWDC 2017 Updates

Todays WWDC 2017 has started with the message for developers “Keep making apps, the world is depending on you”.

Some of keynotes:

Mac:
1. High Sierra macOS releases.
2. Safari improvement - 80% faster than chrome now.
3. Split screen support.
4. Machine Learning in Chrome
5. Apple File System for Mac
6. Metal2 improves graphics potential more. 80% graphics speed improved.
7. Metal support VR

Watch:
1. watch OS4 releases.
2. Play music while workout.
3. Siri based new watch faces.

iOS:
1. iOS 11 releases.
2. Message app - end to end encryption. iCloud Sync (Synced across all iOS devices)
3. Apple pay - Person to person easy transaction. (Free with Debit card ; 3% charge on Credit Card transactions)
4. Machine Learning in Siri, it understands the context and your interests too.
5. Multi Language Translation support.
6. Loop/Bounce effects on Photos. 
7. Spot light search on handwritten text - Notes app.
8. Virtual object placements on Live photo.
9. Core ML - Machine Learning Kit.
10. Image recognition improves 6x faster than Google pixel.
11. Maps inside Malls.
12. Do not disturb while driving.
13. Provided AR Kit for development.  Becomes world largest AR platform.

iPad pro:
1. sizes 10.5” and 12.9”.
2. Camera 12Mp rear and 7Mp front.
3. 40% graphics performance improved. A10x fusion 6 core processor.
4. Drag drop files/datas among multiple apps.
5. Apple pencil is hugely promoted.
6. File management application, integrates other 3rd party FS services too.

tvOS:
1. Amazon prime is joining Apple.

HomePod:
1. Home kit enabled siri support.
2. Inbuild speakers/woofers/A8 processor chip.


# Xcode 9 with Swift 4 released. 


Other Features: 
Photos App support GIF
Automatically send WIFI passwords to nearby devices. 
One Hand keyboard support, which will move the keyboard keys to the left/right with less spacing b/w keys)
Airplay 2 - Multi room audio & shared playlists. 
Music App: Its a social network now. Find people & playlists. 
Leaves behind iPhone 5, iPhone 5c, 4th gen iPad by dropping support for 32-bit apps. 
iOS removed native Social networks(fb, twitter, Vimeo, Flickr) integrations. 
Auto fill passwords for Apps, just like it is in Safari. 

Monday, April 17, 2017

Memory Management in Objective-C

Note: This article was written a very long back in the period of Xcode 6.

Any application that runs on a device needs some sort of space in memory(RAM) during runtime in order to store any necessary data to be displayed or handled in the app. Any program that runs on the device needs to manage their memory based on the system resources(RAM Memory) by controlling or managing the lifetime of all the objects created for the app.
iOS Applications does this through a process called 'Object Life Cycle Management' Or Otherwise called as 'Object Ownership'.
This Ownership scheme is handled through a 'Reference Counting' mechanism, which uses a tracking mechanism internally to detect the number of owners for each object.


Reference Counting Rules:
  • Reference Count = 1, when an object is created and the Creator is the owner here.
  • Reference Count +1, whenever a new owner is added.
  • Reference Count -1, whenever an owner releases its reference.
  • When Reference Count == 0, then the object is destroyed by automatically calling the dealloc() method. You never have to call the dealloc() manually, calling release on an object does it automatically.

Memory Management in Objective C is basically defined as “the process of allocating memory during your program’s runtime, using it, and freeing it when you are done with it”.

There are 2 ways to accomplish it:
  • MRR (Manual Retain Release)
  • ARC (Automatic Reference Count)



MRR (Manual Retain Release):
iOS Version: iOS 4.3 and below
Xcode Version: 4
Using this method you can explicitly manage your memory by keeping track of all the objects you own using the Reference Counting mechanism.


ARC (Automatic Reference Count):
iOS Version: iOS 5 and above
Xcode Version: 4.2
This method also uses the Reference Counting mechanism, but does it automatically by inserting the memory management method calls on behalf of you at the compile time. Thus, ARC uses MRR behind the bars and handles the dirty stuff of managing the memory for you.


So, before iOS5 was introduced, developers used MRR to manually manage their memory to use the system resources efficiently.
Even after iOS5 and Xcode4.2, Apple provided its developers with the ability to use the MRR method by setting a Boolean value in Build Configuration of the project to “Objective C Automatic Reference Counting”. Hence setting it to Yes means, the app uses ARC and NO means, the app uses MRR method.



This is a screenshot of how to set the variable of Memory Management method in Xcode6:





Let's take a look at the MRR method.



MRR (Manual Retain Release):

In Manual Retain Release method, it is completely your own responsibility to claim and relinquish the ownership of any object you create in your program, which can be done by the following memory management methods:

Method
Behaviour
Alloc
Creates an object and claims ownership of it.
Retain
Claims ownership of an already existing object.
Copy
Copies an object and claims ownership.
Assign
Assigns an object without owning it.
Release
Relinquish ownership of it and destroys it immediately.
Autorelease
Does same as Release, but postpones it after its use.



In Objective C, an object is Created or Initialised as follows:

NSString *string = [[NSString alloc] initWithFormat:@”String Variable holding content”];

When an object is initialised with any memory management methods(alloc, copy, retain), it is not just created but it's Reference Count is also increased by 1.
Thus, the above 'string' object now has a Reference Count of 1.

Now, if the same object is retained as follows:

[string retain];

Now, the Reference Count is increased to 2.
Thus, it needs to be released twice to destroy the 'string' object completely from the memory, which could be done as follows:

[string release];


The basic idea behind the MRR method is that, you need to balance between the memory allocation and deallocation methods in order to free up the memory.
Suppose, if you forget to deallocate the object, then the object remains there until your application quits, thus it means there is a “Memory Leak”. It wont have any severe effect, if the object occupies tiny space, but if your program keeps on doing this spontaneously, then the system may run out of memory and your application might crash.

Also, if you try to release an object too many times, which is called as “Dangling Pointer”, means the pointer of an object refers to an invalid memory address, since the object is already deallocated thus freeing up from the memory. This situation means that your program will most likely crash.

Let's have a look at an example:

{
Person *aPerson = [[ Person alloc] init];
// ...
NSString *name = aPerson.name;
// ...
[aPerson release]
}

Here, since we create an object for Person model/class, we take ownership of it, hence we deallocate/release it after its use. Whereas, we don't take ownership of the string object, hence we don't release it.
When you don't release 'aPerson' object, then it creates a memory leak, which could be detected by using the tools provided within Xcode. Just tap on Product --> Analyze, you will be pointed to the exact line of code of where it causes the leak.


dealloc() Method:
When we release an object, dealloc() method is called and thus we can release the instance variables of any custom classes as follows:

@interface Person : NSObject
@property (retain) NSString *name;
@property (retain) NSString *age;
@end

@implementation Person
- (void)dealloc
{
[_name release];
[_age release];
[super dealloc];
}
@end

dealloc() method releases and frees up the memory of those instance variables.
Also, you need to call the dealloc method of the super class.

Explaining Assign:

Let's have a look at the following example:

We have two models:

// Car.h
#import
#import "Person.h"
@interface Car : NSObject

@property (nonatomic) NSString *model;
@property (nonatomic, retain) Person *driver;

@end



// Person.h
#import

@class Car;

@interface Person : NSObject

@property (nonatomic) NSString *name;
@property (nonatomic, retain) Car *car;

@end


@class Car, says the compiler that there is a class called Car that already exists, thus it wont keep importing the class again & again, since we have already imported Person class in Car.


In the main.m class:

// main.m
#import
#import "Car.h"
#import "Person.h"

int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *john = [[Person alloc] init];
john.name = @"John";
Car *honda = [[Car alloc] init];
honda.model = @"Honda Civic";
honda.driver = john;
NSLog(@"%@ is driving the %@", honda.driver, honda.model);
}
return 0;
}


This says that i have initialised a Person object and assgined it to the driver of the Car object, which means Car object holds an ownership of Person object.

Now, add this line:
john.car = honda;
after this line:
honda.driver = john;
in main.m class, which means that the Person object also owns the Car object, which means that both the objects owns each other and the memory management system wont be able to destroy them even if they are no longer needed. This is called as the “Retain Cycle”, which is a bad memory leak.

Fortunately, it is also easy to fix by just setting a weak reference to any of the properties holding back the other object.


So, now let's do it for the Car object in Person class as follows:
@property (nonatomic, weak) Car *car;

Now, the Person object has a non-owing relationship to the Car object.


Thus, the basic idea behind the bar is that No 2 objects must have retained relationship when they are linked to each other, thus avoiding the Retain Cycle.



ARC (Automatic Reference Count):
ARC introduces new @property attributes. You should use strong in case of retain and weak in case of assign.
You don't have to keep/maintain the Reference Count of any objects, and all the memory management methods are inserted into the code during the compile time on your behalf.

dealloc() method:
You don't need to release the instance variables and call the super class's dealloc() method as we did in MRR method, which is automatically done for you by ARC.
That means there is no need for you to include the dealloc() method in the class at all.


Summary:

To develop modern applications, developers must choose ARC to leave the headache of Memory Management to the system and thus focus on the app features in order to get the best out of it.
ARC handles all the memory management stuff except that you have to play carefully with the Retain Cycles.

Sunday, April 16, 2017

Linking my Imaginea profile here

My profile on the Imaginea blogger has the following posts which are based upon the libraries that i developed for the Fontli app:

SparkButton
PlainLoaderView


Thursday, November 17, 2016

Swift 3 Updates

Hey there,

I just went through the list changes in Swift3 and i'll log an abstract of those changes here.



1.) First parameter label: Now, all the function params have labels.

2.) Omitted needless words:
Some Examples from Swift2 -> Swift3:
  • UIColor.blueColor() -> UIColor.blue,
  • numbers.minElement() -> numbers.min(),
  • "Hi there".lowercaseString -> "Hi there".lowercased,
  • Similarly 'uppercased' for 'uppercaseString'


3.) UpperCamelCase has been replaced with lowerCamelCase for enums and properties:
  • NSURLRequest(URL: someURL) -> URLRequest(url: someURL)
  • NSTextAlignment.Left -> NSTextAlignment.left
  • UIInterfaceOrientationMask.Portrait -> UIInterfaceOrientationMask.portrait

4.) GCD and CoreGraphics API's are changed from C style to Swift:

GCD:
In Swift2:
"dispatch_after(dispatch_time, dispatch_get_main-queue(), {})"

In Swift3:
"DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {}"

CoreGraphics:
In Swift2:
guard let context: CGContext = UIGraphicsGetCurrentContext() else { return }
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
CGContextSetLineWidth(context, 2)
CGContextDrawPath(context, .Stroke)

In Swift3:
guard let context: CGContext = UIGraphicsGetCurrentContext() else { return }
context.strokeColor = UIColor.red().cgColor
context.lineWidth = 2
context.drawPath(mode: .Stroke)


5.) Avoid calling with class names: 
'Self' to call class methods & 'self' to call instance methods. (Previously we'd to use class name to call class methods)

6.) Class prefixes removed:
NS removed from Timer, UserDefaults, FileManager, Data, Date, Calendar, URL, URLRequest, UUID, NotificationCenter and more

7.Swift Package Manager: Official dependency manager

8.) Inline Sequences:
In Swift2: sequence(first: someView, next: { $0.superview }) { // someView, someView.superview, someView.superview.superview,... } In Swift3: for x in sequence(first: 0.1, next: { $0 * 2 }) .prefix(while: { $0 < 4 }) { // 0.1, 0.2, 0.4, 0.8, 1.6, 3.2 }

Sunday, November 6, 2016

Hybrid Mobile App Filepath Case-Sensitive Issue

I have been yearning to learn Hybrid App Development for a very long time. To get started, i wanted to be good at fundamentals in  20+years old web technology - HTML/CSS/JS. Hence, i did this course in Coursera first and then did a round of R&D for the Hybrid frameworks and decided to start with Ionic, as i found Ionic framework to be the best in the industry as far as i know. Hence, did this Ionic course in Udemy, which is good starter for programmers. 
Enough of my story. 
Jumping into the context; After finishing up the course(not really finished, just watched the On-Demand videos as usual), i tried to create an app during which i faced an issue which was very weird, i.e., everything was working fine on the browser, but it wasn't working on the actual mobile devices, both iOS & Android, which were supposed to be the target devices. 
First, the catch i made was that the issue was consistent on both (iOS&Android) these devices, so definitely its not an OS specific issue. 
Next, i tried to print logs around all the code where the issue was producing and found that  one specific library(randomColor.js) was the cause of the issue, which was added at last (as far as i remembered), so i put logs around the code used in my JS file which were printed in the device console and noticed that none of my code written after that library's code was getting executed. 
To confirm that the randomColor.js is the cause, i just commented out all the library related code from my JS file & everything was working fine on all the devices, so the culprit was that library. Now, i wanted to find out if the issue was in my code or in the lib code. I saw that the lib had hundreds of stars & active contributors, so there's less chance of having any such critical issue left out in the prod version. 
So, finally, i decided to check the lib integration process from the start again & found out that a very minor mistake i did was the ROOT Cause of this major issue. 
The issue was that there was a case-sensitive file name typo i made in the import statement in my "index.html" file. 
This was the path of "randomColor.js" file in my project:
"Lib/randomcolor/randomColor.js"
But, i imported this lib in "index.html", like this:
"Lib/randomColor/randomColor.js"

Did you notice?
Yes, that Su**ing CAPITAL 'C' (Have marked in Bold above) was the culprit. 

Since, browsers does case-insensitive search for JS files, whereas both the native mobile platforms does case-sensitive file search, hence i was faced with the issue after integrating "randomColor.js" with typo in file import code. 

It might not be a very big issue, but it wasted a lot of my time, hence thought of logging it here, thus hoping to save someone else time with this crap. 

Thanks for taking out your time to read my stuff. 😊