By A Beginner

Every Expert Was Once A Beginner

Protocols in Objective – C — July 6, 2015

Protocols in Objective – C

Protocols

As we have interfaces in Java and C#, and like abstract class in C++ similarly in Objective – C we have ‘protocols‘. A protocol is a list of methods that your confirming class promises to implement. It is not a real class, It can only declare methods and cannot hold any data. We can use Protocols to mark classes as having certain capabilities, like the ability to be copied, to be serialized and deserialized, or to act as a data source for some other class. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal. Thus protocols are used as an alternative to the subclassing.

Declaring Protocols

To declare a custom protocol we can use the below syntax.  A protocol can be declared in the ‘.h’ file of a class before the interface declaration.

@protocol MyProtocolName

//My protocol methods declaration

@end

You can mark a class as conforming to above protocol by declaring so in the class’s interface:

@interface SomeObject : NSObject 

@end

Here the class ‘SomeObject’  conforms to the protocol ‘MyProtocolName‘, thus the class ‘SomeObject’ must have to implement all the methods declared in the conforming protocol.

Protocols are not same as subclassing a class, where your class inherits number of methods and can choose to override some or all of them. Where as, conforming to the protocol means that you must implement all of the required methods that the protocol specifies.

To create an object conforming to the protocol we use the syntax as below:

@property(weak) id someConformingObject;

Here the object ‘someConfirmingObject’ confirming to ‘MyProtocolName’ is of type ‘id , so that it could be an object of any class at the run-time, but it is guaranteed that it implements the methods listed in the protocol.

Example for implementing custom Protocol:

Consider the two classes classA and classB , where classB contains the protocol called ‘MyProtocol‘. Here my classA has the strong reference to the object of classB and it conforms to the protocol ‘MyProtocol‘. In classB we have an object delegateObj of type id conforming to the protocol MyProtocol, this object holds the weak reference to the object of classA. The implementation for the methods in the protocols will be found in classA. Using the delegateObj in classB we can invoke the protocol methods in classA. i.e classB delegates its job to classB.

classA
//classA.h

@interface classA :NSObject 

@end

//classA.m
#import "classA.h"
#import "classB.h"

@implementation classA
-(void)initClassBObj
{
   classB *objB = [[classB alloc] init];
   objB.delegateobj = self;   //setting weak referenc of classA to classB object
}

-(void)myProtocolMethod
{
    //Delegated Task from classB
}

@end

classB
//classB.h

@protocol MyProtocol 
-(void)myProtocolMethod;
@end

@interface classB : NSObject
@property (weak) id delegateObj; //Holds the weak reference to classA object
@end

//classB.m

#import "classB.h"

@implementation classB

-(void)delegateTaskToClassA
{
 [self.delegateObj myProtocolMethod]; //This call delegates the task to protocol 
 //method in classA
}

@end

Other Details on Protocols:

Formal Protocols:

A formal protocol is a set of methods that must be implemented in any conforming class. This can be seen as a certification regarding a class, ensuring that it is able to handle everything that is necessary for a given service. A class can conform to an unlimited number of protocols.

Informal Protocols:

The informal protocol is not really a ‘protocol‘ ,instead it creates no constrains upon the code. But it is ‘informal‘ in nature and contributes for code auto documentation. This lets us to group methods by application field, so that it organize its classes consistently. We use the concept called ‘class category‘ to implement informal protocols.

 To Know more refer:  Protocol


@property in Objective – C — June 28, 2015

@property in Objective – C

The keyword ‘@property’ in Objective-C can can be associated to a data member, to tell how the assessors can be automatically generated by the compiler. Which help us writing less code and saving the development time.  When the data member (instance variable) as a property ,it becomes available to the other classes to access or change its value using the accessors methods.

Declaring property

The properties can be declared in the @interface or the @implementation of the class with the appropriate attributes, but best practice is to declare them in the @interface of the class if it has to be accessed or changed by the other class. when declaring the property we can specify how the instance variables are exposed to other classes.

When you declare a property, you are telling other objects that getter and setter methods for accessing and changing one of the class’s instance variables exist.

Syntax for declaring the property in Objective-C:

@interface SomeClass : NSObject

@propert type name;
       //or
@property (attributes) type name;

@end

Property Attributes

Property attributes describe to other objects(and to the compiler) how the property behaves. The possible access specifiers are :

  • strong –   This property is a strong (owning) reference to an object. Using strong and weak properties controls whether the object referred to by the property stays in memory or not.
  • weak – This property is a weak (nonowning) reference to an object. When the object referred to by this property is deallocated, this property is automatically set to nil.
  • copy – This property’s setter copies any object passed to it, creating a duplicate object.
  • assign – This property’s setter method simply assigns the property’s variable to whatever is passed in, and performs no memory management.
  • readonly – This property does not generate a setter method, rendering the property read-only by other classes. (Your class’s implementation code can still modify the property’s variable, however.)
  • readwrite – This property generates both getter and setter methods. (This attribute is set by default—you need to explicitly use it only when overriding a superclass’s property.)
  • nonatomic – This property’s setter and getter do not attempt to get a lock before making changes to the variable, rendering it thread-safe.
  • getter=…, setter=… – Used when you want to change the default name of the accessors.                                               Eg:- @property (copy,getter=myGetter,setter=mySetter) NSObject *myObject;

 In a garbage-collected environment, retain is not different from assign. But in that case, the attributes __weak and __strong can be added.

Keywords @synthesize and @dynamic

@synthesize : This means that, unless developer already did it, the compiler should generate the accessors by it self, confirming to the constraints that were used in the property declaration. (With ARC all the properties are auto-synthesized and no need to explicitly synthesize the property explicitly in the @implementation)

@implementation A
@synthesize myProperty =_myProperty; //bind to "_myProperty" rather than "myProperty"
//(which does not even exist here)
@end

@dynamic : This means , it is up to the developer to provide the expected implementations of the accessor methods (a mere setter if read-only was specified when declaring the property; getter and setter otherwise).

If you do choose to mark a property as @dynamic, you need to implement the getter and setter methods yourself as shown below:

@implementation MyClass
@dynamic myProperty;
- (int) myProperty {
// this is the getter method for this property
      return 123;
}

- (void) setMyProperty:(int)newValue {
// this is the setter method for this property
}
@end

To understand more about @property refer:

  1. Encapsulating data

KVO In Objective – C — June 17, 2015

KVO In Objective – C

What is KVO ?(Key Value Observing)

KVO – Key Value Observing ,is the feature provided by COCOA which allows an object to register itself to be notified when another object changes the value of one of its properties. Here the controller would ask the model object for notification when the data changes , when the controller receives the notification from the model, the view is updated.

KVO simplify the process of registering for notifications ,and notifying any changes any objects that need to be told of the changes. Any property of an object can be observed , as long as that property’s name is key value coding compliant.

How to Register an Object For Change Notifications?

An object can register itself to be notified of the changes of its properties by the other object, by  telling the object to be observed the following : the object that should be notified when the property changes, the name of the property that should be observed, and the information the observer should be told about when the when change happens. Optionally , we can also include the pointer or object reference that should be passed to the method that is run when the change in the value of the property happens.

Eg: –

[aPerson addObserver:self
          forKeyPAth:@"personName"
             options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
             context:nil];

In the above snippet we see that the object we add an observer for the ‘personName’ property of the object ‘aPerson’ to be observed by the ‘self’ object , which is notified with the old and new values of the property ‘personName’ of the ‘aPerson’ object.

Once the object has registered itself as the observer of another object, this object recieves the message ‘observeValueForKeyPath:ofObject:change:context:‘. This message has the following parameters:

  • The key path of the property that changed -[personName]
  • The object whose property changed -[aPerson]
  • An NSDictionary that contains information about the change -[change dictionary]
  • The context variable that was passed in when addObserver:forKeyPath:options:context: was called -[nil]

The change dictionary contains the different information dependin on what options wer passed in when the observer was added.

Eg:-

  • NSKeyValueObservingOptionNew :  then the dictionary contains the NSKeyValueChangeNewKey key, whose object is the value that the property has been set to.
  •  NSKeyValueObservingOptionOld : then the dictionary contains the  NSKeyValueChangeOldKey key, which can be used to get the previous value of the property.

Eg:-

The example for how an object can handle the aPerson object changing its personName property :

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
       if ([keyPath isEqualToString:@"productName"]) {
           NSString* newPersonName = [change objectForKey:NSKeyValueChangeNewKey];
        // tell the appropriate view to update, based on the newPersonName variable.        }
}

How to Notify the Observers of the Changes?

Whenever implementing the key-value observation, the objects need to notify their observers when their properties change.

If the properties are declared using the ‘@property’ syntax and have compiler synthesize the accessor methods, then the object is automatically notify any registered observers when the setter methods are called.

If Objective-C properties syntax is not used for declaring the properties, or if you override the setter methods for a property , you need to manually notify the system of the changes that are being made.To do this, you call the willChangeValueForKey: and didChangeValueForKey: methods on the self object. This allows the key-value observing system to keep track of the previous and new values of a property.

Eg: – How to override the setter method for the personName property of aPerson object.

- (void) setPersonName:(NSString*)newPersonName {
          [self willChangeValueForKey:@"personName"];
          productName = newProductName;
          [self didChangeValueForKey:@"productName"];
}

To know more on KVO refer:

  1. Introduction to Key-Value Observing Programming Guide
  2. Understanding Key-Value Observing and Coding
KVC in Objective-C — April 29, 2015

KVC in Objective-C

 What is KVC?

KVC- Key Value Coding in Objective-C provides a mechanism for accessing the object properties indirectly. KVC makes use of strings to identify the objects properties ,rather than using the accessor methods or accessing them directly through instance variables.

KVC is the core technology of the binding technologies used by the controller layer (MVC), also a key mechanism behind the Core Data. By using KVC we can make the application scriptable, also using the KVC methods can simplify the applications code.

What are Keys and Key Paths?

Key is a string that identifies a specific property of  an object. Typically, a key corresponds to the name of an accessor method or instance variable in the receiving object.

Eg: For a "Person Object" the keys would be firstName,lastName,emailId,address,empId. and so on..

Key Path is string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and subsequent key is evaluated relative to the value of the previous property.

Eg: In case of the person object again the key path 'address.street' would get the value of the address property of the receiving 'person' object , and then determine the 'street' property relative to the 'address' object.

How to get attribute values using Key – Value Coding?

We can easily get the attribute values using the method, ‘valueForKey: ‘ which return the value for the specified key, relative to the receiver. If there is no accessor or instance variable for the specified key, then the receiver sends the message valueForUndefinedKey:  to itself . The default implementation of this method raises an exception NSUndefinedKeyException; The sub classes can override this behavior.

Eg: NSString *fName = [person valueForKey:@"firstName"];
Here the string fName holds the value for the property 'firstName' of the object 'person'.

How to set attribute values using Key – Value Coding?

The method setValue:forKey: sets the value of the specified key, relative to the receiver, to the provided value.If the specified key does not exist, the receiver is sent a setValue: forUndefinedKey: message. The default implementation of this method raises an NSUndefinedKeyException ; however,subclasses can override this method to handle the request in a custom manner.

The method setValue:forKeyPath: behaves in a similar fashion, but it is able to handle a key path
as well as a single key.The setValuesForKeysWithDictionary: sets the properties of the receiver with the values in the specified dictionary, using the dictionary keys to identify the properties. The default implementation invokes setValue:forKey: for each key-value pair, substituting nil for NSNull objects as required.

One additional issue that you should consider is what happens when an attempt is made to set a non-object property to a nil value. In this case, the receiver sends itself a setNilValueForKey: message. The default implementation of setNilValueForKey: raises an NSInvalidArgumentException . Your application can override this method to substitute a default value or a marker value, and then invoke setValue:forKey: with the new value

Get Sample XCode Project showing use of KVC Here!

To know more on KVC refer:

1.Key Value Coding Programming Guide by apple.

2.Understanding Key-Value Observing and Coding

Blocks in Objective-C — April 18, 2015

Blocks in Objective-C

Blocks in Objective-C allows you to store the chunks of code in variables. Blocks can be assigned to a variable , passed to functions, and generally treated like any other value. Also the blocks can be called as the function, and they capture the state of the things as they were when the block was created.

A simple block would look something like this :

int i = 5;
void (^someCode)() = ^{
NSLog(@"The value of i is %i", i);
};

We can invoke the above block like a function :

someCode();  //This prints  “The value of i is 5”

Here we see that the value of the variable ‘i‘ was captured during the creation of the block , hence it its value is 5 when used within the block. Thus when a variable outside a block is referenced within that block, the value of that variable at the moment of the block’s creation is captured and is available for the block’s code to use.

Blocks allow you to defer the execution of something until you need it to actually happen. This makes them very useful in the context of animations (“when the animation’s done, do this thing”), for networking (“when the download’s done, do something else”), or in general user interface manipulation (“when I return from this new screen, do some work”). They also allow you to keep related pieces of code close together. For eg:- using Blocks we can avoid writing a method to filter the array elements having prefix “Apple” as below.

// Filter an array of strings down to only strings that begin with the word
// "Apple"
NSPredicate* filterPredicate = [NSPredicate predicateWithBlock:^(id anObject) {
NSString* theString = anObject;
return [theString hasPrefix:@"Apple"];
}];
NSArray* filteredArray = [someArray filteredArrayWithPredicate:filterPredicate];

 Blocks Syntax

[Return Type] (^ [Variable Name]) ([Parameters]);

With reference to the above syntax we can define the block variable as shown:

  • A simple block which returns no value and takes no parameters will be defined in the following ways
void(^myBlockVariable)(void);      
void(^myBlockVariable)();    //Since the block takes no parameters
  •  A block block which takes input parameters will be defined by adding the parameters in the paranthesis at the end –
void(^myBlockVariable)(BOOL booleanParameter, NSString* objectParameter);

Once a block variable has been declared, it must have a block assigned to it before it can be called.

void(^myBlockVariable)(BOOL parameter);   //Declaration of the block variable
myBlockVariable = ^(BOOL parameter) {    // Assigning Block to the block variable   
// Code goes here.
};
                               
                                         ---OR---
void(^myBlockVariable)() = ^{ //Declaration and initialization of a block variable 
// Code goes here.                  //This block takes no parameters
};

Once we have defined the block it can be called as a we invoke the function like : myBlockVariable();

Using Blocks as parameter in Methods

Since the block in objective C is treated as any other value and assigned to a variable ,it can be passed as the parameter to a function. This is a key feature of the block ,since it allows the caller of the methods to provide the code at the moment they call the method.

The method accepting the block as a parameter can be declared as below:

- (void) someMethod:(void(^)(BOOL aParameter)) handler;

The implementation of this method would be:

- (void) someMethod:(void(^)(BOOL aParameter)) handler {
// Call the passed-in block:
handler(YES);
}                                        

We can call the above method like this

[anObject someMethod:^(BOOL aParameter) {
// The called method will call this method
}];

We can simplify the deceleration of the block variable by defining the block type , this reduces the amount of typing the code to declare a block variable and using it. Also it makes sure that all the block we use are of the same type.

// somewhere in your source code, outside of a function or method:
typedef void(^ABlockType)(BOOL aParameter);

// and later, in a function:
ABlockType myBlock = ^(BOOL aParameter) {
// do some work
};

We can use the above declared block as the method parameter as shown here:

- (void) someMethod:(ABlockType)handler; //This looks much tidier...!

Be Careful when using blocks

When a block is created, it is stored on the stack memory. So when we create a block, store it in a instance variable of the method , and then if we return from this method the block is removed from the memory but the instance variable still points to where it was. Thus on calling this block now would crash as the block no longer exists. This problem can be solved by copying the block to the heap , and making it to be in the memory as long as needed.

// myBlockProperty is a property of this class that can store the block.
void(^myBlockVariable)() = ^{
// code goes here
};
self.myBlockProperty = myBlockVariable; // INCORRECT! The block
// won't exist after this function returns, and calling it will crash.
self.myBlockProperty = [myBlockVariable copy]; // SAFE. The
// block will be copied and stored on the heap, and stick around.

Modifying the Local variables from within the block

Since the block captures the value of the variables that was during the creation of the block. In order to modify the value of this variable from within the block, we must declare the variable marked with the __block keyword.

__block int i = 0;                    //Declaring the variable with __block keyword
void(^myBlock)() = ^{                 // A simple block which modify the value of 'i'
i = 4;
};
myBlock();
NSLog(@"i is now %i", i);             // will print "i is now 4"
References:

Books: Learning Cocoa with Objective-C ,By -Jon Manning, Paris Buttfield-Addison, and Tim Nugent.

To know more:
Categories in Objective-C — April 4, 2015

Categories in Objective-C

Objective-C provides a feature for defining the new methods for an existing class even for the class whose source code is not available to you. One can make use of categories when their is a need to add new methods to the predefined classes such as COCOA classes-‘NSString etc.’ without sub-classing it .

A category is a group of methods for a class which are available to all through the class and can be used as the methods declared in the interface of the method. This helps to split up the class having numbers of methods in to several interface and implementation files, which helps in maintaining the large projects.The category name indicates that the methods are the additions for the class defined earlier and not a new class.

Consider a class ‘car’

// car.h

#import <Foundation/Foundation.h>

@interface Car : NSObject

-(void)startEngine;

-(void)applyBreak;

@end

Now consider the above ‘car’ class for which we want to add some new methods/capabilities (maintenance),we can do this by using categories as below.

// car+Maintenance.h

#import “car.h”

@interface Car (Maintenance)

-(void)maintainanceTyre;

-(void)maintainanceEngine;

@end

The implementation file for this category ‘maintenance’ would be as below:

// Car+Maintenance.m

#import Car+Maintenance.h

@implementation Car (Maintenance)

-(void)maintainanceTyre                                 //method 1 defination

{

}

-(void)maintainanceEngine                                 //method 2defination

{

}

@end

Now the methods ‘-(void)maintenanceTyre’  &  ‘-(void)maintenanceEngine’  will be available to all the objects of the ‘car‘ class.

#import <UIKit/UIKit.h>

#import Car.h

#import Car+Maintenance.h”                                      //category 

int main(int argc, char * argv[]){

@autoreleasepool {

Car *car1 = [[Car alloc] init];

//using methods from the class ‘car’

[car1 startEngine];

[car1 applyBreak];

//using additional methods from the category maintenance for the car1 object

[car1 maintenanceTyre];

[car1 maintenanceTyre];

}

}

Download : Sample XCode project on categories and extension Here!

Categories in Objective-C —

Categories in Objective-C

Objective-C provides a feature for defining the new methods for an existing class even for the class whose source code is not available to you. One can make use of categories when their is a need to add new methods to the predefined classes such as COCOA classes-‘NSString etc.’ without sub-classing it .

A category is a group of methods for a class which are available to all through the class and can be used as the methods declared in the interface of the method. This helps to split up the class having numbers of methods in to several interface and implementation files, which helps in maintaining the large projects.The category name indicates that the methods are the additions for the class defined earlier and not a new class.

Consider a class ‘car’

// car.h

#import <Foundation/Foundation.h>

@interface Car : NSObject

-(void)startEngine;

-(void)applyBreak;

@end

Now consider the above ‘car’ class for which we want to add some new methods/capabilities (maintenance),we can do this by using categories as below.

// car+Maintenance.h

#import “car.h”

@interface Car (Maintenance)

-(void)maintainanceTyre;

-(void)maintainanceEngine;

@end

The implementation file for this category ‘maintenance’ would be as below:

// Car+Maintenance.m

#import Car+Maintenance.h

@implementation Car (Maintenance)

-(void)maintainanceTyre                                 //method 1 defination

{

}

-(void)maintainanceEngine                                 //method 2defination

{

}

@end

Now the methods ‘-(void)maintenanceTyre’  &  ‘-(void)maintenanceEngine’  will be available to all the objects of the ‘car‘ class.

#import <UIKit/UIKit.h>

#import Car.h

#import Car+Maintenance.h”                                      //category 

int main(int argc, char * argv[]){

@autoreleasepool {

Car *car1 = [[Car alloc] init];

//using methods from the class ‘car’

[car1 startEngine];

[car1 applyBreak];

//using additional methods from the category maintenance for the car1 object

[car1 maintenanceTyre];

[car1 maintenanceTyre];

}

}

Download : Sample XCode project on categories and extension Here!

iOS:To seprate group of ANAGRAMS in an array — January 17, 2015

iOS:To seprate group of ANAGRAMS in an array

Here is the code for grouping and printing the set of anagrams in an array.If any better solutions please Comment.


- (void)viewDidLoad
 {
 [super viewDidLoad];
 //self.view.backgroundColor=[UIColor blueColor];
 // Do any additional setup after loading the view, typically from a nib.
 NSString *tmpStr1;
 NSString *tmpStr2;
 NSMutableArray *newArr=[[NSMutableArray alloc] init];
 BOOL Var=NO;
 int i,j;
 NSArray *arr1=[[NSArray alloc] initWithObjects:@"star",
 @"rats",
 @"arts",
 @"car",
 @"rac",
 @"arc",
 @"abcde",
 @"bcdea",
 @"cdeab", nil];
 for (i=0; i<[arr1 count]; i++) {
 for (j=i+1; j<[arr1 count]; j++) {
 tmpStr1=[arr1 objectAtIndex: i]; //star
 tmpStr2=[arr1 objectAtIndex:j]; //rats
 if ( tmpStr1.length == tmpStr2.length) { //4==4
 [newArr addObject:tmpStr1]; //newArray=[star]
 for (int k=0; k<tmpStr2.length; k++) {
 //Get the letter by letter in tmpStr2
 NSString cmpStr=[NSString stringWithFormat:@"%C",[tmpStr2 characterAtIndex:k]]];
 if ([tmpStr1 rangeOfString:cmpStr.location == NSNotFound) {
 Var=NO; //Characters in tmpStr2 not found in tmpStr1
 } else {
 Var=YES; //Characters in tmpStr2 found in tmpStr1
 }
 }
 //if all the letters in string tmpStr2 are present in string tmpStr1
 if (Var) { 
 //add the second string i.e. tmpStr2 to the array newArr
 [newArr addObject:tmpStr2]; 
 }
 }
 else
 {
 i=j; 
 //remove the duplicate strings in the array newArr
 //print the anagram set to log
 NSLog(@"NewArr::>%@",[[NSSet setWithArray:newArr] allObjects]); 
 //remove the objects in the array for the next set of anagrams
 [newArr removeAllObjects]; 
 //Controll goes to this line::> for (j=i+1; j<[arr1 count]; j++)
 continue; 
 }
 }
 }
 NSLog(@"Arr2::%@",[[NSSet setWithArray:newArr] allObjects]);
 NSLog(@"Arr1::%@",arr1); //To print the original array
 }



Find on Git: Here!
iOS:Database in applications usingFMDB Wrapper Class —

iOS:Database in applications usingFMDB Wrapper Class

  We can include the database in our iPad/iPhone applications with the help of   SQLite and FMDB wrapper class. Here is how we can achieve it with following simple steps.

1. First with the help of Mozilla Firefox SQLite plug-in create a MyDatabase.sqlite file and save it in your project folder.

2.Get the FMDB Wrapper classes from the git hub project  https://github.com/ccgus/fmdb unzip it and navigate to the fmdb folder (fmdb-master.zip\fmdb-master\src\fmdb) and copy this to your Xcode project.

 3. Write this piece of code in your appdelegate.m  in   file to make a connection to your MyDatabase.sqlite file  and save the path to your database in NSUserDefaults so that we can use it when we are doing any DB operations.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

//-------------------DataBase connection----------------------

    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];



    // To Get the path of the database file during runtime of application

    NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"MYDatabase.sqlite"];

    NSLog(@"Database path: %@",databasePath);



    if ([fileManager fileExistsAtPath:databasePath] == NO) {

        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"MYDatabase" ofType:@"sqlite"];

        [fileManager copyItemAtPath:resourcePath toPath:databasePath error:&error];

    }

    //save the database path in userdefaults  so that you can use it for connecting to database and making database operations

    [[NSUserDefaults standardUserDefaults] setValue:databasePath forKey:dbPath];

    [[NSUserDefaults standardUserDefaults] synchronize];

}

4. In ViewController.m file of your project import the two header files

#import "FMDatabase.h"
#import "FMResultSet.h"

then write the following code to connect to the database and make the insertion and selection operations in your app Database.

- (void)viewDidLoad
{

[self insertDataInDB];

//array  dbResultArray Has the resultant rows retrieved from db by SELECT Query

NSArray *dbResultArray=[NSArray arrayWithArray:[self getDataFromDB]] ;

//To store the data retrieved in a variables for use 

//Use your convenient way to store the  retrieved  data  and use it in your app

for(int i=0 ; i<dbResultArray.count;i++){
  NSString *str1=[[dbResultArray objectAtIndex:i] valueForKey:@"column1Value"];
  NSString *str2=[[dbResultArray objectAtIndex:i] valueForKey:@"column2Value"];  
.
.  
.
  NSString *strN=[[dbResultArray objectAtIndex:i] valueForKey:@"columnNValue"];
}//String 
}

This below method inserts the data in to database :

-(void)insertDataInDB
{
//Connec to database
NSString *dbPath=[[NSUserDefaults standardUserDefaults]valueForKey:dbPath];
FMDatabase *localDB = [FMDatabase databaseWithPath:dbPath];
[localDB open];
NSString *queryStr;

queryStr=[NSString stringWithFormat:@"INSERT INTO table_name (Collumn1,Collumn2,Collumn3,Collumn4,....,CollumnN) VALUES (Value1,'Value2','Value3','Value4',.....,'ValueN')"];

  if (![localDB executeUpdate:queryStr]) {

          //NSLog(@"failed Inserting data to DB: %@", [localDB lastErrorMessage]);

      }
 [localDB close];

}

This below method  returns the array of Dictionary containing the Retrieved data from database:

-(NSMutableArray *)getDataFromDB
{
//Connec to database
NSString *dbPath=[[NSUserDefaults standardUserDefaults]valueForKey:dbPath];
FMDatabase *localDB = [FMDatabase databaseWithPath:dbPath];
[localDB open];
NSMutableArray *tempArrayV=[[NSMutableArray alloc]init];     
NSString *queryStr=[NSString stringWithFormat:@"SELECT * from table_name"];
FMResultSet *resultQuery = [localDB executeQuery:queryStr];
//After the query is executed 
while ([resultQuery next]) {
NSDictionary * DataDict =[NSDictionary dictionaryWithObjectsAndKeys:
[resultQuery stringForColumn:@"Column1"],@"column1Value",
[resultQuery stringForColumn:@"Column2"],@"column2Value",
[resultQuery stringForColumn:@"Column3"],@"column3Value",
.
.
.
[resultQuery stringForColumn:@"ColumnN"],@"columnNValue",nil];
[tempArrayV addObject:DataDict];
}
return tempArrayV;
[localDB close];
}

Hope this will help you to implement the Application with the database support.

iOS – Architecture — January 14, 2015

iOS – Architecture

                   
                iOS is an operating system for the iPhone’s (an Apple Inc Product). It is derived from core OS X technologies ( an OS for MAC pc) .The iOS includes the OS X Kernel , BSD Sockets for Networking  and objective-C and C/C++ compilers for native performance. iOS 7.0 is the latest release of iOS on June 10 2013.


The iOS has the layered architecture, different layers are in the below figure.

Cocoa Touch is a UI framework for building software programs to run on the iOS operating system (for the iPhone, iPod Touch, and iPad) from Apple Inc.
Cocoa Touch mainly contains the classes implemented  in Objective-C, an object-oriented language that is compiled to run at incredible speed, yet employs a truly dynamic runtime making it uniquely flexible. Because Objective-C is a superset of C, it is easy to mix C and even C++ into your Cocoa Touch applications.
The framework’s of this layer provides provide the basic  app infrastructure and support for the key technologies ( .i.e Multitasking ,touch-based input, push notification and many  high level system services.)
UIKit Framework: This frame work provides the crucial infrastructure for implementing graphical ,event driven, apps in iOS.
The Media layer contains the graphics, audio, and video technologies you use to implement multimedia experiences in your apps. The technologies in this layer make it easy for you to build apps that look and sound great.
The technologies of this layer are listed as below:


Core Services Layer:

This Layer contains basic system services for apps. Core Foundation and Foundation Frameworks are the key services provided by this layer, which define the basic types that all apps use it also has the technologies which supports the features like location, iCloud,social media and networking.
Some of the High-Level Features and Frameworks provided by this layer are:

This layer contains the low-level features on basis of which the other high-level features are built.Even though we do not use any of these features directly in our  apps ,they used by the frameworks which are used by our application.We can make use of these features when we need to implement the security features  or communicating with an external hardware accessory.
Frameworks provided by this layer are: