Monday, May 28, 2012

UITextField Overview



UITextField Overview

In my last blog i have explained how to work with Xcode by showing a small demonstration on UITextField, in this post i will cover some of the methods and properties of Textfield, so lets begin

Open Xcode and display a textfield in the window of iPhone simulator in case you forgot how to do that hers the link to my blog which will help you (TextField display).

The UITextField is just like a textbox where the user enters data via keyboard and is the most commonly used UIControl (UI stands for User Interface) UITextField is a class in the UIKit framework which contains lots of controls with the help of which you can design your iPhone app. Alright now we have some basic understanding about UITextfield so lets begin

Setting the text
There are two ways by which you can set the text of TextField the first method is by property called text and second method is by using an object function called setText.

To use them you have to make the object of UITextField and then you can use any one of the methods

[objtxtfield setText:@"Radix"];
OR
objtxtfield.text = @"Radix";

both will give you the same output which will look like this


snap1.jpg
Place Holder
setPlaceholder is a method which will display a text by default prior to the user entering anything and you can use this method like this

[objtxtfield setPlaceholder:@"iphone by radix"];

which will give you the following output


snap2.jpg
and when the user will start editing the textfield then the default text will disappear and if the textfield contains no data then the user can see the default text in this case it will be iphone by radix.

Font
you might want the data to appear in your text field with a specific font and size so in this case you can use the setFont method.



[objtxtfield setFont:[UIFont fontWithName:@"Georgia" size:25]];

which will make the text look something like this


snap3.jpg

textAlignment
you can set where the text must appear like to left, right, or center with the help of the property textAlignment

objtxtfield.textAlignment = UITextAlignmentCenter;

and this will make the text look like this


snap4.jpg

Editing 
now there might be a time when you want the textfield to be read only so in this case you have the setUserInteractionEnabled boolean method and you can use this object method like this

[objtxtfield setUserInteractionEnabled:NO];

also there might be a scenario where you might want the text to be cleared as soon as the user begins editing the textfield so in that case you can use the clearsOnBeginEditing property and set it to YES

Display image in textfield

Now let's say you want to display an image in a textfield


UIImageView *objimage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"apple.png"]];
  [objtxtfield setLeftView:objimage];
  [objtxtfield setLeftViewMode:UITextFieldViewModeAlways];

When the above code lines executes you will get the following result in your simulator

snap1_1.jpg


Adjusting the text size in UITextField


Text displayed in the textfield can be dynamically sized based upon the width of the textfield. The text being typed will be available on the screen and will keep on shrinking down upto a default limit of font size 17. So here i make my font size huge like some what of 30 in size and then i start typing in my text field.

objtxtfield.text = @"Large text";

[objtxtfield setFont:[UIFont fontWithName:@"Georgia" size:30]];

[objtxtfield setAdjustsFontSizeToFitWidth:YES];

now if you do this you application at start will look like this


snap3_1.jpg

and once you start typing on the textfield it will automatically shrink its size and then you will have this view given below


snap4_1.jpg
Hiding and showing the keyboard
For this you have a protocol method named textFieldShouldReturn

- (BOOL)textFieldShouldReturn:(UITextField *)textField
all you have to do is first set the delegate property of the object of textfield to self


objtxtfield.delegate = self;

and then in the textFieldShouldReturn method you have to write the following code


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
 [objtxtfield resignFirstResponder];
 return YES;
}

and in order to show the keyboard you have to write the following code


[objtxtfield becomeFirstResponder];


Foundation Framework


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

Properties in Objective C


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

snap2.jpg

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....

SDK, IDE, Framework and API


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.


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.

NSString and NSMutableString


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



snap1.jpg


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:


snap2.jpg

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

@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 

snap2.jpg

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.
snap4.jpg