Sunday, September 27, 2015

Functions in Swift -- IOS

//Functions is commonly used to group a series of statements together to achieve a specific objective

//To declare a function

func helloSwift(){

    print("hello Swift")

}

//To invoke a function

    helloSwift() // the word "hello swift" will be printed 


Function that Return value-

//To declare a function
 func helloSwift() -> String{

    return "hello Swift"
}

//To invoke a function and catch return in var "result"
var result = helloSwift()

//"result" is hello swift

print(result)

Conditional Statements in Swift -- IOS

If / else Statement-

//Deciding on different path of execution . Decision making is done with if and  else statements --

//Executed if marks greater than or equal to 60

if marks >= 60
{
    print("you score first division")
}
else
{
    print("you not score first division")


}

Chained conditions -
//In case where there are more than two possible paths of execution . you can use the if/else if/else block

var marks = 60

if marks >= 60
{
    print("you score first division")
}
else if marks >= 50
{
    print("you  score second division")

}
else if marks >= 40
{
    print("you  score third division")
}
else
{
    print("you failed")
}

Logical Operators - && and ||

Use && operator to make complex decisions involving two (or more) conditions . The result is "true" only if both conditions evaluate true. 

//output is true 
print(true && true)

//output is false
print(false && true)

//output is false
print(true && false)

//output is false

print(false && false)


The ||  operator works in the same way . The result is true  if either one of the conditions evaluates to true

//output is true 
print(true || true)

//output is true
print(false || true)

//output is true
print(true || false)

//output is false
print(false || false)



Example of using && and ||

func getResult (english: Int, science: Int){

    if(english >= 60 && science >= 60)
    {
    print("Passed both test")
    }
    else if(english >= 60 || science >= 60)
    {
        print("pass at least one test")
    }
    else
    {
    print("fail")
    }

}


//Passed both test
getResult(50, 60)

//Pass at least one test
getResult(60, 70)

//Fail

getResult(8, 8)


Nested if/else statements -

var gender = "M"
var age = 18
var discount: Int;


if gender == "M"{
    //execute if gender is male 
    if age > 18{
        discount = 10 //discount (10) if male is above 18 
    }else{
        discount = //discount (5) if male is below 18 
    }
    
}else{
        //execute if gender is not male 
    if age > 18{
        discount = 20
    }else{
        discount = 15
    }

}



Constant Declaration & Mathematical Operations in Swift -- IOS

In swift, use the "let" Keyword to declare constant. For constant , value cannot be changed after declaration .

let number = 100

//This is not allowed, value cannot be changed after declaration




//similarly for constant, you can explicitly declare the data type
let numbers: Int = 7




Mathematical operations -

For numbers , the usual mathematical rules apply . You can use any of the following operations : *, +, -, /, % on numbers. 

//Division operations 

// Int Divide Int = int 

var x = 1/2
result = x = 0


//Int divide decimal value = decimal value 
var y = 1/2.0
result = y = 0.5


//Operations on String

let string = "hello" + "world"
result=  "helloworld"

let str = "3" + "4"
result = "34"

   Code - Checking for even number
// If the reminder of "evenNumber" dividing my 2 is 0 , "evenNumber is an even number"

Var evenNumber = 8
print (evenNumber % 2)

result =  0






Saturday, September 26, 2015

Variable Declaration in Swift -- IOS

//Variable Declaration -

To declare a variable , the data type of the variable is inferred from the value assigned to the variable .

var str = "Hello, playground"

//change the value of the variable 


str = "Hello  Swift"


//Error --- The "str" variable has a datatype of string , and cannot be re-assinged as an Int , float etc..


//You can also explicitly declare the data type in variable 

var name :String = "Hello , Swift"

var age: Int = 45


commonly used data types include String,  Int,  Float,  Double, Bool.  Sample variable declaration for the different data types - 

var S:String = "Swift"
var W: Bool = true
var I: Int = 67
var F: Float = 13.3
var T: Double = 2.2


You can use x.dynamicType to find out the data type of var "X"

let string = "Hello World!”
let array = [“Hello”, “Swift”]
let dictionary = [“dictionary”: 1]

print(string.dynamicType) // "String"

// Get type name as a string
String(string.dynamicType) // "String"
String(array.dynamicType) // "Array<String>"
String(dictionary.dynamicType) // "Dictionary<String, Int>"

// Get full type as a string
String(reflecting: string.dynamicType) // "Swift.String"
String(reflecting: array.dynamicType) // "Swift.Array<Swift.String>"
String(reflecting: dictionary.dynamicType) // "Swift.Dictionary<Swift.String, Swift.Int>"

Monday, July 27, 2015

Remove UIMENUITEMS (e.g --->copy , define , share etc ) from UIMenuController


- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if (action == @selector(paste:))
{
return NO;
}
if (action == @selector(select:))
{
return NO;
}
if (action == @selector(copy:))
{
return NO;
}
if (action == @selector(cut:))
{
return NO;
}
if (action == @selector(delete:))
{
return NO;
}
if (action == @selector(promptForReplace:))
{
return NO;
}
if (action == @selector(_setLtoRTextDirection:))
{
return NO;
}
if (action == @selector(_setRtoLTextDirection:))
{
return NO;
}
if (action == @selector(selectAll:))
{
return NO;
}
else
{
return YES;
}

}


                             OR 


- (void)webViewDidFinishLoad:(UIWebView *)webView 
{

  // Disable user selection
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
   
// Disable callout
    [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];


}

Sunday, March 22, 2015

Wednesday, February 25, 2015

IOS

*****************************Design Pattern*********************

  • Creational: Singleton and Abstract Factory.
  • Structural: MVC, Decorator, Adapter, Facade and Composite.
  • Behavioral: Observer, Memento, Chain of Responsibility and Command.
   
MVC - model , view , controller 
Singleton - one instance exists [UIApplication sharedApplication]
Facade Design - Facebook API
Decorator pattern- Decorator pattern dynamically adds behaviors and responsibilities to an object without modifying its code.implementations of this pattern: Category and Delegation.
category - Category is  that allows you to add methods to existing classes without subclassing
Delegation - , Delegation, is a mechanism in which one object acts on behalf of, or in coordination with, another object

Observer pattern -  one object notifies other objects of any state changes. e.g Notifications and Key-Value Observing
The memento pattern -The memento pattern captures and externalizes an object’s internal state. In other words, it saves your stuff somewhere. Memento pattern is Archiving. NSCoder class


*****************************Dynamic Typing*********************

Dynamic Typing:
Determining class of a Object at runtime is called dynamic typing.
Dynamic binding:
Determining the method to invoke at run time is called dynamic binding. 

*****************************Obj c and c++*********************

Objective C Allows method name and variable name exactly the same.
-It doesn't have the constructor or destructor instead,it has init and dealloc which must be called explicitly.
-It uses '+' and '-' to differentiate factory and instance methods.
-It uses dynamic linking.
-It got categories .


Auto layout - IOS 6

store data - plist , nsuserdefault , sqlite, core data

Shallow copy is also known as address copy.
deep copy you copy data

What is advantage of categories? What is difference between implementing a category and inheritance?
You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without subclassing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality.

polymorphism  - Ability of base class pointer to call function from derived class at runtime is called polymorphism.at runtime, super class reference is pointing to whatever subclass,

App delegate is declared as a subclass of UIResponder 

@interface - It’s a keyword used to declare the Class
@implementation - It’s a keyword used to define the Class
@synthesize - to generate getters and setters automatically from compiler

Atomic and non- atomic -  nonatomic and atomic are related to multithreading environment . If a property has an attribute as “nonatomic” that means multiple threads can modify that property concurrently. If the attribute is “atomic”, the threads would be given access atomically. So “Atomic” is thread safe while “nonatomic” is thread unsafe. 

@ dynamic  - It tells compiler that getter and setter are not implemented by the class but by some other class. e.g The Managed object classes have properties defined by using @dynamic

mustitasking - IOS4

Json - Form iOS 5 Onwards we are using NSJSONSerialization inherited from NSObject Base class.

categories and extensions-  Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) — it’s meant to be just that, an extension.

KVC - KVC(Key Value Coding)  Normally instance variables are accessed through properties or accessors but KVC gives another way to access variables in form of strings.In this way your class acts like a dictionary and your property name.

KVO (Key Value Observation): The mechanism through which objects are notified when there is change in any of property is called KVO.

A protocol, declared with the (@protocol syntax in Objective-C) is used the declare a set of methods that a class that “adopts” .id<MyProtocol> instanceOfClassThatImplementsMyProtocol;protocol Directives :- @optional, @required.

run loop - . A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none. Run loop management is not entirely automatic. You must still design your thread’s code to start the run loop at appropriate times and respond to incoming events.










Wednesday, February 11, 2015

NSMutableString to set some part of sting BOLD -- IOS

 NSString *textStr = @"This is a good boy";

NSRange rangeBold = [textStr rangeOfString:@"good"];

 UIFont *changeFont = [UIFont boldSystemFontOfSize:13];
        
  NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys: changeFont, NSFontAttributeName, nil];
        
 NSMutableAttributedString *mutAttrTextViewString = [[NSMutableAttributedString alloc] initWithString:textStr];
        
  [mutAttrTextViewString setAttributes:dictBoldText range:rangeBold];

        
       

    YOUR_TEXT_VIEW.attributedText = mutAttrTextViewString;