Rules of Swift Initializers


Rule 1: A designated initializer must call its immediate superclass designated initializer
Rule 2: A convenience initializer must calls initializers of the same class
Rule 3: A convenience initializers must ultimately call the designated initializer

Simple Case:















Complex Case

























Reference

Constructs in Objective C and Swift

Classes, Structs and Enums are called Constructs and all three of them allow your program to store, organize or manipulate data in different ways with different capabilities.

Classes
  • General Purpose, flexible construct that becomes the building blocks of your program code.
  • Have properties and methods that provide data storage and functionality to constructs
  • Can use inheritance
  • Can use initializers and de-initializers when setup or tear down when they are created or destroyed.
Structs
  • Structs in Swift can have Properties and Methods (Swift Only)
  • Can use initializers (Swift Only)
  • No Inheritance
  • Passed by copy ( this can be advantage/disadvantage based on the needs)
Enums:
  • Way to group related elements
  • Can include functions (Swift only)
  • Can use initializers (Swift only)

Operators in Objective C and Swift

Common for Objective C and Swift
  • Assignment Operator ( = )
  • Arithmetic Operator
    • addition +,
    • Subtraction -, 
    • Multiplication *,  
    • Division /
  • Remainder (Modulo) Operator %
  • Unary plus operator (+), Unary minus operator (-), unary operator is prepended directly on the value it operates on.
  • compound assignment/short hand operators (x+=y, x-=y, x*=y, x/=y, x%=y, x&=y, x|=y, x^=y)
  • Increment (++) & decrement operator (—) {int x=9, int y: y= ++x , y = - - x } (Removed in Swift 3)
  • Relational/Comparison operators 
    • Equal to (a == b)
    • Not equal to (a != b)
    • Greater than (a > b)
    • Less than (a < b)
    • Greater than or equal to (a >= b)
    • Less than or equal to (a <=  b)
  • Logical Operator 
    • Logical Not (!a)
    • Logical AND (a && b)
    • Logical OR (a || b)
  • Ternary Conditional Operator ( if condition? expression 1 : expression 2 )
Swift Only
  • Range Operator 
    • Closed Range Operator '1…10', includes 1 and 10 in this range.
    • Half Open Range Operator '1..~10 , includes 1 but not 10
  • Nil-Coalescing Operator (x??y)
The nil-coalescing operator (x ?? y) unwraps an optional x if it contains a value, or returns a default value y if x is nil. The expression a is always of an optional type. The expression y must match the type that is stored inside x.

The nil Coalescing operator is shorthand for the below code:

x != nil ? x! : y

The code above uses the ternary conditional operator and forced unwrapping (x!) to access the value wrapped inside a when x is not nil, and to return x otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

Guard in Swift

Guard statement is similar to IF statement except the fact that body of code executes when the condition in guard statement is evaluated to false.

var citizenAge:Int  //Declare a variable of type Integer

citizenAge = 65

guard citizenAge < 60  else {
// Here citizen age is 65, the guard condition is evaluated to false and the below statement is executed.
print("Senior Citizen")
return
}
print("Not a Senior Citizen") // this is executed when guard condition is true.

Guard Statement can also be used for optional binding

var playerScore:Int?    //Declare a variable a of type Optional Integer, which might or might not have value (for e.g if player did not bat, he might not have any score)

func updatePlayerScore (playerScore:Int?){
    guard let score =  playerScore else {
        print(“Player did not bat“)
        return 
    }
    print("Player score is \(score)")
}
  • Unlike if statement values assigned in the Guard statement are still available after the Guard statement through out the remaining scope that encloses the Guard Statement
  • Guard Statement are typically written at the top of the enclosing scope

Swift Data Types

There are two fundamental data types in Swift

Value Types 
  • Int, Floating-Points, Booleans, Characters, Strings , Arrays, Dictionaries and Tuples (which are implemented as Structures)
  • Optionals (which are implemented as Enumerations)
Reference Types
  • Classes
  • Functions and Closures 

Optionals in Swift


var a : Int            // create a swift variable of type int
var b = a + 10      //compiler will thrown an error because a is not initialized

Alternative to above

When your using ‘?”/optional , that means your explicitly telling the compiler that a may or may not have the value.

var a : Int?
var b = a! + 5     // the compiler suggest to unwrap the optional, this is called force unwrapping and program will crash if in case a does not have value so force unwrapping of optionals is always dangerous and should not do it unless your sure about var holding a value.

then what is the safe way to deal with optionals? answer is optional binding 

if let nonOptionalValue = a {
var b = nonOptionalValue + 5  // if a is nil, this statement is not executed and force unwrapping is not required in this case because we knew that a is not nil and has a value for sure.

}

Pointers

In Objective C all objects are referenced using pointers:

A pointer is a variable which stores memory address instead of value itself.

how big is int, 4 bytes
how big is char, 1 byte
how big is String, image or video?  we often don’t know and it might even change during our program so we need more flexible way to manage objects and pointers are one way of allowing us to do that.

Using pointers allows us to pass around the objects (just by passing around the address of object) without having need to copy them which is time consuming and inefficient  

E.g.   NSString* welcomeString;
         NSDate* todayDate;

welcomeString = @“Welcome to Objective C”;

Here the string 'Welcome to Objective C’ string is not directly stored in ‘welcomeString’ instead the address/memory location of 'Welcome to Objective C' is stored in ‘welcomeString which is contrary to 'int highScore = 100’ where ‘highScore’ variable directly stores value. ( this is because objects are more complex than primitive types)

if you want to make and use of simple object, we need pointers to reference them.
Note: Explicit use of pointers in Swift is not required unlike Objective C. e.g let someInstance = SomeClass ( ) whereas in objective C it is SomeClass *someInstance = [SomeClass alloc] init];

Structures in Objective C and Swift

Structure is a complex data type which contains individual elements which defer in type. 
There are many situations in programming where discrete types have to be identified together as one unit. In this situations we make use of Struct.

Structs are used to represent a record, Suppose you want to keep track of your books in a Library. you might want to track the following attributes about each book.

Struct Book {
Title
Author 
Subject
Book ID
};

Struck Person {
Name
Age
Height
Weight
Gender
Color
};

Individual elements of Struct are referred to as members

Unlike Objective C, classes in Swift, structures can have methods, properties, initializers, and conform to protocols. The main difference between classes and structures is that classes are passed by reference, while structs are passed by value.

Set vs Array

The main difference is that NSArray is an ordered collection and NSSet is an unordered list of unique elements.

Set
  • Primarily access items by comparison   
E.g    let ingredients = [“Tea Powder”, “Sugar”, “Hot Water”, “Milk”, "Cardamom"]
          if ingredients.contains(“Cardamom”) {
print(“It is Cardamom Tea”)
}
  • unordered
  • does not allow duplicates
Array

  • Can access items by Index
  • Ordered
  • Allow duplicates

Dynamic Typing & Dynamic Binding:

Dynamic Typing in Objective C means that the class of an object type id is unknown at the compile time and is discovered at the run time based on the message sent to the Object.

Dynamic typing allows us to declare a variable that is capable of storing any type of object regardless of its class origin, this is achieved using the Objective C id type, the id type is a special, general purpose data type that can be assigned an object of any type.

Dynamic binding takes this one step further by allowing methods on object type id to be called without prior knowledge of the type of an object currently assigned to the variable.


Different states of an iOS app

Different states of an iOS app:
  1. Not Running 
  2. Inactive
  3. active
  4. Background
  5. Suspended
1. Not Running

App is usually in this state when it is not launched yet or was running but was terminated by the system 

2. Inactive

App is running in the foreground but is currently not receiving any user events (it may be executing other code though), App usually enter into this state only briefly as it transitions into different state.

3. Active

App is in the Foreground and receiving user events. This is normal mode for foreground apps.

4. Background

App is in the background and executing code. Most app enters into this state briefly on their way to being suspended. However the app that request the extra execution time may remain in this state for a period of time.

5. Suspended

App is in the background but not executing code. The system moves apps to this state automatically and does not notify them before doing so, while suspended app remains in memory but does not execute any code

When a low memory condition occurs, the system may purge suspended apps without notice to make more space for foreground app.

Apps must be prepared for termination to happen any time and should not wait to save user data to perform other critical tasks. Suspended apps receives no notification when they are terminated.


if the app is currently running in the background and not suspended, the system calls  applicationWillTerminate: of its app delegate prior to termination. The system does not call this method when the device reboots.

Swift Only Features


Below are the features introduced in swift and not present in Objective C
  • 'repeat while' which is conceptually equal to 'do while' in C/Objective C
  • guard statement
  • 'Any' (keyword using which arrays dicts can store objects of discrete type)
  • 'fallthrough' (using which we can allow implicit fall-through in switch statement which is not default in Swift unlike Objective C)
  • 'AnyObject' conceptually equivalent to id in Objective C
  • Optionals
  • Tuples
  • Range Operator

About Swift


Swift is the safe, interactive and concise language. Following are the notable things in Swift language for objective C developers.
  • Explicit pointer usage is not required in Swift unlike Objective C
  • No semicolon is needed at the end of the statement
  • Conditional expression is not necessarily included in parenthesis for if, while, do while, switch statements
  • print() is used to print messages to the console in swift
  • var and let are two important keywords in swift programming language
  • var is used to create mutable object variables and let is used to create immutable object variables in Swift
  • var should be either initialized or type defined. if you creating variables in the class context, you must initialize variables using default/custom initializers.
  • Do while not allowed in Swift instead use repeat while which is conceptually equivalent.
  • Just like Objective C, multiple inheritance is not supported by Swift, however a Swift class can conform to multiple protocols.
  •  String interpolation in Swift is a way to construct a new string value from a mix of constants, variables, literals, and expressions by including their values in a string literal. Each item you include in a string literal is wrapped in a pair of parenthesis prefixed by a backslash.
  • Swift does not support implicit conversion of values E.g var i = 4 cannot be changed to i = 4.5 during some point in the program.
  • Swift infers the data type implicitly based on the initialized values
  • functions in swift are conceptually equivalent to methods in objective C
  • Arrays are zero based and accessed using sequence of integers.
  • Arrays are strongly typed/type safe (all the elements in the array should be of same data type unless using “Any" keyword)
  • Dictionaries are strongly typed in Swift (elements in dictionary is accessed using unique key)
  • All the keys in the dictionary should be specific type and all the values in the dictionary should of specific type. All the keys and values of dictionary can be of same type but the number of types dictionary can accommodate is restricted to two unless using “Any” keyword
  •  Switch statement in swift must be exhaustive, can provide ranges of values ( closed range operator and half open range operator). No automatic implicit fall though unlike Objective C- code , but can be achieved by writing fallthrough control transfer statement.

How to Localize iOS Apps

Localization?

The practice of adjusting a product functional properties and characteristics to accommodate the language, cultural , political and legal differences of a foreign market or country.

Localization of iOS Apps?

Making your app available in different languages based on the targeted users.
Apart from the Apps that are downloaded from App Store, there are decent number of iOS Apps that exists on your device by default.

E.g. Phone, Messages, Maps, Calendar, Music, Camera, Stocks, App Store, Game Center, Contacts, Whether, Photos, Notes etc.

The above default apps which are provided by Apple already support localization.

E.g.  Settings > General > International > Language

and the select the language you prefer, you can notice all the default apps provided by Apple will reflect the changes according to user preference. This is because all the apps are facilitated with the language and cultural specific content.

These changes might reflect in apps ( downloaded from App Store) also depending on the factor whether they are localized or not.

Approaches

In general there are two ways which are predominantly used to localize the iOS Apps.
  1. Default Approach
  2. Within the App 
Default Approach









Naming convention  "Localizable.strings" is must and should for default approach. Once that is done, next step is add the supported languages.



In the above step, check all and click on finish for time being. In the later part of this post, it will be clear why we need to check this files after adding each language.






Please check mark all the language in the above step, by default only english is checked.

Now look at the magic Xcode does, for every language you added Xcode automatically creates different version of the same file i,e "Localizable.strings" on the left hand side pane of project window as shown below.


Now Let us try to understand how iOS manages to display the appropriate content from those language specific string files.



 Xcode creates a separate .lproj directories for each new language you add. if you open those directories you will see the .string files related to specific language. Apart from .string files you can manually copy-paste all the other resources like images, audio files, video files etc into the directories.

Note: You also realize that the files you checked after adding each language are existing in each of this directories....you can check language specific XIB files over there to appear in this directory.




 In the run time iOS loads all the resources from respective directories based on the users language preference. Let us see with some simple example which contains Heading Label and Desc Label and see  how it works in real time.

Create Heading and Desc Label in ViewController.m as shown below.


Code Snippet for the above Screenshot:

    UILabel *headingLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 70, 300, 30)];

    


//The below line of code is responsible for retrieving the content from appropriate language specific .string file using NSLocalizedString.


    headingLabel.text =[NSString stringWithFormat:NSLocalizedString(@"HeadingLabel", nil)];
    
    headingLabel.textColor = [UIColor blackColor];
    headingLabel.textAlignment = NSTextAlignmentCenter;
    headingLabel.backgroundColor = [UIColor clearColor];
    headingLabel.font = [UIFont fontWithName:@"Arial-BoldMT" size:16.0];
    headingLabel.hidden = NO;
    headingLabel.highlighted = YES;
    headingLabel.lineBreakMode = YES;
    headingLabel.numberOfLines = 0;
    [self.view addSubview:headingLabel];
    
    UILabel *descLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 300, 200)];

//The below line of code is responsible for retrieving the content from appropriate language specific .string file using NSLocalizedString.

    descLabel.text =[NSString stringWithFormat:NSLocalizedString(@"DescLabel", nil)];
    
    descLabel.textColor = [UIColor blackColor];
    descLabel.textAlignment = NSTextAlignmentLeft;
    descLabel.backgroundColor = [UIColor clearColor];
    descLabel.font = [UIFont fontWithName:@"" size:18.0];
    descLabel.hidden = NO;
    descLabel.highlighted = YES;
    descLabel.lineBreakMode = YES;
    descLabel.numberOfLines = 0;
    [self.view addSubview:descLabel];

Now go to Localizable.strings(English) file and paste the key value pairs for the above UI Elements.


"HeadingLabel" = "LOCALIZATION(ENGLISH)";
"DescLabel"= "Localization is the process of adapting a product to meet the language, cultural and other requirements of a specific target environment or market so that users can use their own languages and conventions when using the app.";

Repeat same thing for Localizable.strings(Spanish).

"HeadingLabel"= "LOCALIZACIÓN (SPANISH)";
"DescLabel"= "La localización es del proceso de adaptar un producto para cumplir los requisitos del lenguaje, culturales y otro de un ambiente o de un mercado específico de la blanco de modo que los utilizadores puedan utilizar sus propios lenguajes y";

Repeat same thing for Localizable.strings(Greek).

"HeadingLabel"= "ΕΝΤΟΠΙΣΜΟΣ(GREEK)";
"DescLabel"= "Ο εντοπισμός είναι πολιτιστικές και άλλες απαιτήσεις της διαδικασίας ένα προϊόν για να συναντήσει τη γλώσσα, ενός συγκεκριμένης περιβάλλοντος ή μιας αγοράς στόχων έτσι ώστε τον οι χρήστες μπορούν να χρησιμοποιήσουν.";


Checkout the below screenshot for reference.


Go ahead and run your project using iPhone (or) iPad Simulator.


How do i switch to Spanish or Greek?

 Settings > General > International > Language> Spanish or Greek,  then press Done

iOS Simulator will reboot the app with new user settings and we need to relaunch the app again to view the reflected changes.

Note: Do not select the language other than what u included, it shows English by default even if you does so.


Navigate to Screen where your app is and relaunch to view the content in Spanish.


Cons of this Approach
  • Users need to leave the app to change the preferences and relaunch it again.
  • Language change will be reflected on all other apps that supports Localization.
Pros of this Approach 
  • Easy to Implement because of Xcode built-in Intelligence
  • Not much of Coding is required.
Within the App Approach

Coming..soon!

Valid architectures of iOS devices?

iOS Devices are powered by the processors based on ARM architecture, comes in different in versions developed overtime, each one added with some improvements.
























iOS developers should ensure to include the valid architectures in project build settings before building the application just to make sure that application runs on all targeted devices.

Apple dropping support for old architectures over the time, the Xcode versions which supports armv7 and armv7s no longer supports armv6. There are some others ways to support all architectures though.

Can I force an iPhone user to upgrade an application?


        In general forcing the user to update our application mandatorily might not go well from user stand point.
        In-spite of the above fact,  Sometime you do have to force an Upgrade for security or other valid reasons. Lot of gaming applications in the market does this sought of updates.
        some of the Financial Enterprise apps which are right there in the App-Store were able to force app users to mandatorily update it to latest version.



How do i do this?

Get Version info Using Itunes web service 

NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=<Your app ID>"];
versionRequest = [ASIFormDataRequest requestWithURL:url];
versionRequest setRequestMethod:@"GET"]; 
versionRequest setDelegate:self];
versionRequest setTimeOutSeconds:100];
[versionRequest addRequestHeader:@"Content-Type" value:@"application/json"]; 
[versionRequest startSynchronous];

Response string of our REST call 


NSString* jsonResponseString = [versionRequest responseString];
NSDictionary *loginAuthenticationResponse = [jsonResponseString objectFromJSONString];
NSArray *configData = [loginAuthenticationResponse valueForKey:@"results"];
for (id config in configData)
{
    version = [config valueForKey:@"version"];
    
}

Compare Both Versions 


NSString *version = @"1.0";
if (![version isEqualToString:[itsUserDefaults objectForKey:@"version"]]) 
{
    UIAlertView *createUserResponseAlert = [[UIAlertView alloc] initWithTitle:@"New Version!!" message: @"A new version of app is available to download" delegate:self cancelButtonTitle:nil otherButtonTitles: @”Update", nil];
    [createUserResponseAlert show]; 
    [createUserResponseAlert release];//Avoid if using Automatic reference counting
}

Redirect User

-(void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *iTunesLink = @"itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftwareUpdate?id=<appid>&mt=8";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];
}

Which object is create by UIApplicationMain function at app launch time?

The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.

How main function of an app gets called during the app launch cycle?

During app launching, the system creates a main thread for the app and calls the app’s main function on that main thread. The Xcode project's default main function hands over control to the UIKit framework, which takes care of initializing the app before it is run.

Name the application thread from where UIKit classes should be used?

UIKit classes should be used only from an application’s main thread.  Note: The derived classes of UIResponder and the classes which manipulate application’s user interface should be used from application’s main thread.

Does iOS support multitasking?

iOS 4 and above supports multi-tasking and allows apps to remain in the background until they are launched again or until they are terminated