Friday, September 24, 2010

Foundation Framework

In many of our projects we see that a header file called #import <Foundation/Foundation.h>
is imported by default today we will have a look at this header file.   

#import<Foundation/Foundation.h>


The above line means that you will be using some of the classes from the Foundation Framework, The objective C foundation framework is a set of classes that are provided to ease the developers in developing the applications.

The foundation framework was developed by the organization called as the NEXT computers as a part of their NEXTStep as part of Next step environment. Whne Next was taken over by Apple Inc then the developers at Apple used Foundation framework as a part of the development for MAC OS X and after the success of MAC OS X they used it for the development for iPhone development kit.

Since the foundation framework took birth at NEXT all the classes which are present and in the foundation framework begin with the letters "NS".

Just recall our string and array demos you have seen that we have used NSObjectNSString,NSArray NSMutableArray all these classes are coming from the foundation framework.

In order to know more about the foundation framework you can click here




Tuesday, September 14, 2010

Properties in Objective C

In this blog i will discuss the following
  1. What is a Property?
  2. Why is it used?
  3. How to declare a property in Objective C?

Property: I will start from my first question and that's What is a Property?

Property is a value that is used for specific purpose although its use may differ from one program to another. With property you can assign a value and extract a value

Now why to use a property?

Well if your having a java or C# background then you must have read books which say that property is used for information hiding, i think that their are better ways of information hiding rather than using a property (My own view).

While using a property in java or in C# you used to write its getter and setter methods, well in Objective C its totally different.

Let's have a look at an example to see how property works in objective C.

In this example i am trying to add two numbers and the data will be coming from the property, just refer the sample code with comments that i have used to explain property

@interface Myclass : NSObject

{

int num1, num2;    //global variables of integer type

}

@property (readwrite,assign) int num1, num2; //set the property for those integer variable


//you use assign in a case where you cannot retain the value like BOOL or NSRect, else use retain


//If you use retain then you become the owner of that particular property and you must release that property once its use is over.


-(void)add;          //add function



@end


Implementation part of the class

@implementation Myclass        


@synthesize num1, num2;   //synthesize will automatically set getter and setter for your property


-(void)add

{

int result= num1+num2;


NSLog(@"Result of addition is %d",result);

}


@end

The final touch that's our main method

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

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Myclass *obj_Myclass = [[Myclass alloc]init];

[pool addObject:obj_Myclass]; //adding object to the pool

obj_Myclass.num1 = 10; //invoking setter method

obj_Myclass.num2 = 20; //invoking setter method

[obj_Myclass add];    //calling the add method

        [pool drain];

        return 0;

}



Their might also be a scenario where you want the property to be read only, well that again is very easy.
The below given code will make your property read only

@property (readonly,assign) int num1, num2;


You can change the value directly by referencing it directly, refer the code below


-(void)add

{

self->num1 = 10; //legal

self->num2 =20; //legal


int result= num1+num2;


NSLog(@"Result of addition is %d",result);

}


Well this was about the properties in Objective C, if i get to know any more details on properties i will surely update the blog regarding the same....

Monday, September 13, 2010

SDK, IDE, Framework and API

There's always a doubt in the minds of many students that sdk, framework, IDE, API are all the same, well it's nothing like that let's have a look at the basic definitions of these different architectures:

SDK: A Software Development Kit (SDK) is a set of tools used to develop applications for a particular platform(Mac, Windows). An SDK typically contains a compiler, linker, and debugger. It may also contain libraries and documentation for APIs. SDKs also frequently include sample code and supporting technical notes or other supporting documentation to help developers. Often the SDK can be downloaded directly via internet many SDKs are provided for free.

IDE: Integrated development environment (IDE) contains certain controls and editor with the help of which designers can design the user interface and write code for each controls in the editor.

Example: Net beans, Visual studio.

Framework: Framework are classes provided by organizations which helps the programmers to perform complex task. Let's say earlier programmers used to code for database using lengthy procedures now that was time consuming so in order to ease their work, programmers will use a framework which will provide them certain classes and function which will help them to do the database connectivity or any other part regarding database within few steps.

Example:COCOA TOUCH (used for making i phone apps), .net framework, Java server faces

API: Application programming interface (API) is an interface between two software with the help of which they can communicate with each other. API is software to software interface (not a user interface) here's an example of API.
When you buy movie tickets and enter your credit card details then the movie ticket website uses an API to send your information to remote application that verifies whether your information is correct or not and once the information is correct the payment is deducted from your account and tickets are issued. At a time the user is only able to see one screen in this case the movie ticket website but behind the scene their are various application working together with the help of API.
Another example of API is facebook which uses google api to communicate with your gmail account to send friend request to your friends.

Tuesday, September 7, 2010

NSString and NSMutableString

NSString: NSString is a class which handles immutable strings (immutable strings are those strings which cannot be changed). 

The mutable subclass is NSMutableString.

NSString declares methods for finding and comparing strings. It also declares methods for reading numeric values from strings, for combining strings in various ways, and for converting a string in different forms (case change such as upper case, lower case etc)

To use Strings in your application you have to import the following header file


NSString.h


You’ve encountered string objects in your programs before.Whenever you enclosed a sequence of character strings inside a pair of double quotes,as in

@"Programming is fun"


you created a character string object in Objective-C.

Now lets have a look at some of the string functions that are more often used while making an application such as:

  1. copy strings.
  2. Append String.
  3. Equality check.
  4. Which string is greater.
  5. change case.
Given below is the sample code with explanation 

//declare a class 


@interface Myclass : NSObject

{

}

-(void)copystring;           //copy one string to another

-(void)copy_string_at_end;  //append string

-(void)Equality_Check;     //check whether string is equal or not

-(void)great_check;       //check which string is greater

-(void)case_check;      //convert from upper case to lower case and vice versa


@end


//implement the class


@implementation Myclass


-(void)copystring

{

NSString *str1 =@"This is string R1"; //str1 is string object

NSString *str2 = @"This is string R2"; //str2 is string object

//copy str1 in str2 and display result

str2 = [NSString stringWithString:str1];

NSLog(@"%@",str2);  //print str2 on console

}


-(void)copy_string_at_end

{

NSString *str1 =@"This is string R1"; //str1 is string object

NSString *str2 = @"This is string R2"; //str2 is string object

//copy str2 at the end of str1

str2 = [str1 stringByAppendingString:str2];

NSLog(@"%@",str2);  //print str2 on console

}


-(void)Equality_Check

{

NSString *str1 = @"Radix";

NSString *str2 = @"RadiX";

//checking whether strings are eaual or not

if([str1 isEqualToString:str2])

{

NSLog(@"str1 = str2"); 

}

else

{

NSLog(@"str1 != str2");

}

}


-(void)great_check

{

//here the strings are lexically compared means their ASCII values are compared

NSComparisonResult compareresult;

NSString *str1 = @"Radix";

NSString *str2 = @"RadiX";

//for case sensitive compare

compareresult = [str1 compare:str2];

//if you don't want to do perform case sensitive comparision then use the following code

//compareresult = [str1 caseInsensitiveCompare:str2];

if(compareresult == NSOrderedAscending)

{

NSLog(@"str1 is less than str2");

}

else if(compareresult == NSOrderedSame)

{

NSLog(@"str1 == str2");

}

else

{

NSLog(@"str1 > str2");

}

}


-(void)case_check

{

NSString *str1= @"this string will be in uppercase";

NSString *str2 = @"THIS STRING WILL BE IN LOWER CASE";

str1 = [str1 uppercaseString];  //convert lowercase to uppercase.

str2 = [str2 lowercaseString];  //convert uppercase to lowercase.

NSLog(@"%@",str1);

NSLog(@"%@",str2);

}


@end


Now into the main method create the object of your class and then call the methods


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

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


    // insert code here...

    Myclass *obj = [[Myclass alloc]init];

[pool addObject:obj]; //adding object to pool

[obj copystring];

[obj copy_string_at_end];

[obj Equality_Check];

[obj great_check];

[obj case_check];

    [pool drain];

    return 0;

}


The output of the above code will look something like this




If you want to know the length of a particular string then you have an object method called as length.

NSLog(@"The length of the string is %d",[str1 length]);


The above code will give you the length of the string str1.


Now let's have a neat workout with substrings section


inorder to begin i have just add a function named :


-(void)Substring_function;


-(void)Substring_function

{

NSString *str1= @"This is string R1";

//The below line of code print the string upto the specified index number starting from the leading character.

NSLog(@"String at index 3 of str1 is : %@",[str1 substringToIndex:3]);

//if you want to print the substring from the specified index then use the below function

NSLog(@"Substring from specified index is : %@",[str1 substringFromIndex:5]);

//now lets say you have a long string and you want string only from a selected index then you can use the below function.

NSLog(@"Substring from a specified index to a specified index is : %@",[[str1 substringFromIndex:3]substringToIndex:6]);

//now lets say you want to locate a particular string inside your string then in that case you can use the below code

NSRange Myrange;  

//NSRange is a structure which is used to describe a range of series such as charcters in a string and objects in an array


Myrange = [str1 rangeOfString:@"R1"];

NSLog(@"The string is found at location : %d and is of length : %d",Myrange.location,Myrange.length);

//but what if the string is not found then what to do

Myrange = [str1 rangeOfString:@"R2"];

if(Myrange.location == NSNotFound)

{

NSLog(@"No such string found");

}

else

{

NSLog(@"The string is found at location : %d and is of length : %d",Myrange.location,Myrange.length);

}

}


The output of the following function will look something like this in the image given below:




In my next blog i will discuss MutableString

Sunday, September 5, 2010

NSArray and NSMutableArray

In Objective C 2.0 we have two classes called as NSArray and other as NSMutableArray, the first question that came into my mind was:

Why are their two classes for Arrays???

Then i found the answer that the objects that you put in NSArray cannot be changed, i.e the size of NSArray does not change and its totally the reverse case in NSMutableArray. This is the reason why in most of the programming for iPhone, developers use NSMutableArray and not NSArray, NSMutableArray are like the array list of Java and C#.

So in my first example i will show you how to display data from NSArray and in my second example i will be using an NSMutableArray to accept the data from the user and display it into the console, so lets have a look at NSArray part first

Open the Xcode IDE and select command line utility and save your project by giving it an appropriate name.

First i have made a class called as Myclass in which i have a object of NSArray which is globally declared and a method where i will be dsiplaying data from the object of NSArray

@interface Myclass : NSObject

{

NSArray *arr;  //global NSArray object

}


-(void)NSArray_Demo;


@end


Now as my declaration part is completed no i will be implementing Myclass using the keyword implementation


@implementation Myclass


-(void)NSArray_Demo

{

arr = [[NSArray alloc]initWithObjects:@"Ravi",@"Riki",@"Faizal",nil];


// here nil indicates the end of array elements

for(int i =0;i<[arr count];i++)

{

NSLog(@"%@",[arr objectAtIndex:i]);

}

[arr release]; //release arr.


@end



Now the final touch


Guessed it right the main method


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

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];


Myclass *obj = [[Myclass alloc]init];

[obj NSArray_Demo];

[pool drain];

    return 0;

}


Run the application by pressing Run from the meny bar and select console and then Build and Go.


The entire code looks like this 



NSMutableArray:

If you want to add, remove or replace data present in array then use NSMutableArray.
For NSMutableArray we will see the following
  1. Accept data from user.
  2. Display the data accepted.
  3. Replace data at a particular index.
  4. Delete a data from a particular index.
As we did in the case of NSArray we will make a class for NSMutableArray examples so that you can get a clear picture, so lets begin

@interface MyMutablearray : NSObject

{

NSMutableArray *Marr;

}


-(void)getdata;

-(void)replacedata;

-(void)displaydata;

-(void)deletedata;



@end


Now we have finished with the declaration part now lets see the implementation part


@implementation MyMutablearray


-(void)getdata

{

Marr = [[NSMutableArray alloc]initWithCapacity:3]; // initialize the array with capacity


//You can also initialize the mutable array just like you did in the case of NSArray in the above example


char chr[10]; //declare a character array

for(int i =0;i<3;i++)

{

scanf("%s",chr);//accept the input from the user

[Marr addObject:[NSString stringWithCString:chr]]; //typecast the c array and add it to the mutablearray

}

}


//The data present at index 0 will be replaced by the new object in this function

-(void)replacedata

{

[Marr replaceObjectAtIndex:0 withObject:@"Ravi"];

}



// This function will display the data present from Mutable array and will show it on the console.


-(void)displaydata

{

for(int i =0;i<[Marr count];i++)

{

NSLog(@"%@",[Marr objectAtIndex:i]);

}

}


//delete a particular index

-(void)deletedata

{

[Marr removeObjectAtIndex:0];

}


@end


Now lets make the object of our class and execute the program so hope into your main method


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

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

MyMutablearray *obj = [[MyMutablearray alloc]init];

[obj getdata];

[obj displaydata];

[obj deletedata];

NSLog(@"Calling displaydata function after deletedata");

[obj displaydata];

[pool drain];

    return 0;

}

after execution you will get the result as shown in the image.



Saturday, September 4, 2010

Objective C basic points to remember


To learn development in mac technology you need to understand the Objective C programming language, if you are aware of oops concept and a little bit of programming then you can understand this language. Before beginning with objective c you should know a few concepts of objective c.

Objective C is object oriented programming in C.

Apple has a neat and clean developer documentation which will guide you through all the    methods and properties that a particular class has.

Objective C is a mixture of small talk and ansi C.

In Objective C (OC) a class is made up of two files one is called as “YourClassname.h” which deals with the declaration part and the other is called as “YourClassname.m” which deals with the implementation part.

-   You declare all the methods and properties that the class will be containing in the .h part and will implement all those methods in the .m part.

Static methods are declared with the help of + sign and non static method are declared with the help of – sign. Example

+ (void)staticmethodName;      //declaration of static method
-(void)nonstaticmethodName;   //declaration of non static method



Both the .h and .m files together make one class.

You declare a class with the help of the directive @interface.


You implement the methods declared in the .h file in the .m file with the help of @implementation directive.


All classes in OC inherit from a super class named NSObject.


NSObject is the most important class in objective c and it is base class of all the classes in objective c.


To create object of a class in OC you need two methods “alloc” which is used to allocate memory for your class and “init” which is used to initialize the memory allocated for the class with the help of the alloc method.


Init method is called as the constructor in objective c.


If you declare a property then there is no need to add getter and setter method for them they are automatically added to your code if you use the @synthesize keyword.


If you don’t use @synthesize keyword then the property created by you will not work.


If you are creating a new project and have the Automatic reference counting (ARC) enabled then you don’t need to worry about memory management and all the dirty work will be taken care by the system itself.


ARC requires strong reference and not weak reference.



If you are not using the ARC mode then you have to manually release all the objects that you have created in each and every class or in each and every function with the help of release keyword. 

Foundation framework is the framework where all the basic data types reside.


If you want to call a function then you have to use the rectangular brackets.


[ yourObjectName methodName ]; // calling object method
[ yourClassName methodName ]; // calling static method








If you are not aware what type of data will a variable be holding then in that case you can declare the data type of that variable as “id” which is capable of holding any type of data.


If you want to add parameter to a function then you have to use the colon.

- (void)printSomething:(NSString*)uservalue;    //function with 1 para
- (void)printUserName:(NSString*)username andLastName:(NSString*)lastname;           //function with 2 para
- (void)printUserName:(NSString*)username andLastName:(NSString*)lastname anduserAge:(int)userage;  //function with 3 parameter



@selector is the directive which is used to call methods of objects.


@protocol is the directive which is used to create protocols for classes, protocols are certain set of rules that each and every class has to follow and not all the methods are compulsory, say if you declare 5 protocol method then you can implement either 3 or 2 or all protocol method.


The self keyword in Objective C points to the memory address of the current class and hence it is also called as a reference or pointer to the current class.


Delegates are called as event handling methods they are called only when an event is being triggered by a particular class or a UI control.


Datasource methods are those methods which arrange the data in the UI control with which the user interact. The source of data can be anything like an array, string, set, dictionary, database etc, and data is arranged in the UI controls as per the code written by the developer in these datasource methods.


- When you create a new project in iPhone then there are 3 frameworks which are added by default:


1. UIKitFramework: This framework contains the header files (Classes) related to the User Interface used to design the screens of the application.

2. CoreGraphics Framework: This framework contains the header files (Classes) related to all the graphical work in your application like for example if you want to give frame or a particular design to any of your UI controls then methods from core graphics framework are used.

3. Foundation Framework: This framework contains header files (Classes) related to the basic datatypes that are used in the project.

Plist: These are called as the property list, by default when you create a project then there is a project plist which is added in your application, the purpose of this plist is to provide support and allow several system level permissions to your application.

You can also add your own custom plist but that would not contain any system related permissions it would only contain the static data that you would wish to display or you may store any app related data.
Data is accessed from the plist through KVC (key value coding) pattern.


SQLITE: If you would wish to save huge data locally then you would need a database, sqlite is a lite version of the sql database and can do this task for you.

That would be it for now I hope by reading all the above data you would get a fair idea about objective C, if there is any point above that you would like me to elaborate a bit then feel free to contact me via mail or comments.


You may download the PDF version of this post from here, and if you have any sort of queries then feel free to contact me via mail or enter your queries as comments.

Until then happy iCoding and have a great day.