Search Posts in my Blog

Monday, 27 February 2012

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 = @"Rahul";
NSString *str2 = @"RahuL";
//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 = @"Rahul";
NSString *str2 = @"RahuL";
//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;
}

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


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 : %@",[str1substringToIndex:3]);
//if you want to print the substring from the specified index then use the below function
NSLog(@"Substring from specified index is : %@",[str1substringFromIndex: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);
}
}


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

NSArray and NSMutableArray


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

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 = [[NSArrayalloc]initWithObjects:@"Rahul",@"Varma",@"Ramesh",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 menu bar and select console and then Build and Go.




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:[NSStringstringWithCString: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:@"Rahul"];
}



// 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;
}

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



Programming language for iPhone


If you are working on some application then you need a programming language, the programming language that you will be using to build applications for iPhone is Objective C, Objective C is object oriented programming in C the editor used for developing application for iPhone is Xcode.


Objective C follows the object oriented syntax from Small Talk and non object oriented syntax from ANSI C. It was invented by Brad Cox and Tom Love in the organization named Step Stone. In today's world where lots of developers are familiar with programming languages such as JAVA, Cpp, C#, VB.NET, objective c will be quite new to them, don't worry its not that hard once if you get the syntax of objective C you will be developing applications for iPhone in no time. So lets have a look at the syntax part of objective C and one more thing since objective C is a super set of C so any C program which you write in Objective C will run smoothly.

Class Syntax:

Class is like a blue print of a building with the help of which you can construct a building. In programming terms class is said to be as a blue print for your objects. Given below is the syntax to declare a class in Objective C.

@interface <#class#> : <#superclass#>
{
<#ivars#> //global variable declaration
}

<#methods#>

@end

Example:

@interface Myclass :NSObject
{
int num; //global variable
}
-(void)fun; // object method

@end

In the above example you can see that Myclass is inheriting from a class called NSObject, NSObject contains two method called alloc and init with the help of which you can create objects for your class. If you don't inherit your class from NSObject then you cannot create objects for your class. alloc will allocate memory for your class and init will initialize your data member and data functions in that allocated memory.

In the above code we have seen only the declaration of our class but what about the implementation part???

In order to implement the above class objective C uses a keyword called as implementation have a look at the given example below:

Example:

@implementation Myclass

-(void)fun
{
printf("hello");
}

@end


Functions: Functions are just a block of code which will do certain task for you as per your code written in them. Now functions are of two types:
  1. Class functions or static functions.
  2. Object functions.
Syntax for class functions or static functions is given below:

+(void) displaydata;

Syntax for object function is given below:

-(void) displaydata;

The + sign is used to make a class level method (static method) and – sign is used to make an object method.

Now lets integrate all the things which we have learned so far in an example

Example:

@interface Myclass : NSObject
{

}
+(void)classmethod; //static method
-(void)objectmethod; //object method

@end

@implementation Myclass

+(void)classmethod
{
printf("You are in class method\n");
}
-(void)objectmethod
{
printf("You are in object method");
}

@end



Object creation: Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples
of real-world objects: your dog, your desk, your television set.

Syntax of object creation:

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

alloc will create a new instance of the class and init will initialize the class level variables and methods. 

Introduction to mobile technology

iPhone are touch screen mobile phones which run on IOS which is a Apple's mobile Operating System and is derived from MAC OSX. Earlier when iPhone was launched in some what around Jan 2007 third party applications were not supported in iPhone but soon Apple announced that they will be introducing certain SDK (Software development kit) with the help of which developers from all around the world can build their own application.


When you are working on any mobile app their are some key features which you must always keep in mind :

  1. Memory: Mobile device have limited memory and a lot of it is already allocated.
  2. Display Capabilities: Different mobile devices have different display size and you need to plan for that.
  3. App speed: Mobile app users want their app to work quickly so as a mobile app developer you must see to it that you app load and work quickly.
  4. User Interface: The user interface of your app must be very friendly.
Now it's time to get some tools. Go to http://developer.apple.com/iphone/index.action
You can download the SDK for free with the basic registration, but to distribute a completed app on the App Store or install your app on the iPhone for testing you need to become a paid
Standard or Enterprise Developer. The SDK comes with a simulator for testing
directly on your Mac, so free registration is all you’ll need for now.

Now let's talk about the IDE where all the coding part will take place but before that we will have a look at the programming language that we will be using to make an iPhone app. The language used is Objective C which is an object oriented programming language it derives it's syntax from Small Talk and C programming. The IDE used for iPhone development and desktop app development for Apple is Xcode, Xcode 4.2 is the latest version. The Xcode suite also includes most of Apple's developer documentation, Interface Builder, modified version of GNU Compiler and supports C, C++, FORTRAN, Objective C, Objective C++, Java, Apple script, Ruby, Python the Xcode uses GNU debugger as a back end for it's debugger. The Cocoa and Cocoa Touch frameworks powers Mac OS X and I Phone OS and are tightly integrated into the Xcode development experience. Cocoa’s high-level APIs make is easy to add animation, networking, and the native platform appearance and behavior to your application with only a few lines of code.

This was a small introduction to XCode and IOS. I will be adding some examples on some of the controls in Xcode later. I hope that this blog was helpful to you. In order to know the features of iphone you can just hit this link iPhone Features