Translate

Wednesday, March 20, 2013

Object oriented programming(oops)concept in Objective-C


Introduction

qObjective-C is implemented as set of extensions to the C language.

qIt's designed to give C a full capability for object-oriented programming, and to do so in a simple and straightforward way.

qIts additions to C are few and are mostly based on Smalltalk, one of the first object-oriented programming languages.



qObjective C is simply a super set of c.

qSyntax of all non object oriented operations are similar as C.

qObjective-C is the primary language used for Apple's Cocoa API, and it was originally the main language on NeXT'sNeXTSTEP operating system.

qRest syntax is taken from smalltalk.
qEverything happens at run time(Every error is just a warning).
Data & Operation
qProgramming languages have traditionally divided the world into two parts—data and operations .

qObject-oriented programming  groups operations and data into modular units called objects and lets you combine objects into structured .
qEvery object has both state (data) and behavior (operations on data).
q such as an ordinary bottle combine state (how full the bottle is, whether or not it’s open, howwarm its contents are) with behavior (the ability to dispense its contents at various flow rates).
            ID
qid is a data type used by
 Objective-C to define a pointer of an 
object .

qAny type of object, as long as it is an object, we can use the id dat a type.
qFor example, we can define an

 object by:

  id anObject;

qnil is the reserved word for null
 object



ex:
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id dataValue;
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print];
// now dataValue gets a complex number
dataValue = c1;
[dataValue print];
[c1 release];
[f1 release];
[pool drain];
return 0;
}

Defining a Class

qIn Objective-C, classes are defined in two parts:
1.An interface that declares the methods and properties of the class and names its superclass
2.An implementation that actually defines the class (contains the code that implements its methods)

qThe declaration of a class interface begins with the compiler directive @interface and ends with the directive @end.
v @interface ClassName : ItsSuperclass
    // Method and property declarations.
    @end

    Inheritance

qObjective-C enables programmer to inherit common methods and properties from other class, known as inheritance.

q Class from methods and properties are inherited known as Base Class and class that inherits known as Derived .

q Every inheritance hierarchy begins with a root class that has no superclass.
ex:
 #import <Foundation/Foundation.h>
// ClassA declaration and definition
@interface ClassA: NSObject
{
int x;
}
-(void) initVar;
@end
@implementation ClassA
-(void) initVar
{
x = 100;
}
@end
// Class B declaration and definition
@interface ClassB : ClassA
-(void) printVar;
@end
@implementation ClassB
-(void) printVar
{
NSLog (@”x = %i”, x);}
@end

int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
ClassB *b = [[ClassB alloc] init];
[b initVar]; // will use inherited method
[b printVar]; // reveal value of x;
[b release];
[pool drain];
return 0;
                   Polymorphism

qpolymorphism in the context of object-oriented programming, is the ability to create a variable, a function, or an object that has more than one form.

qThe purpose of polymorphism is to implement a style of programming called message-passing in the program.


qThe ability of objects to respond differently to the same message or function call.
ex:
// Shared Method Names: Polymorphism
#import “Fraction.h”
#import “Complex.h”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo: 1 over: 10];
[f2 setTo: 2 over: 15];
[c1 setReal: 18.0 andImaginary: 2.5];
[c2 setReal: -5.0 andImaginary: 3.2];
// add and print 2 complex numbers
[c1 print]; NSLog (@” +”); [c2 print];
NSLog (@”---------”);
compResult = [c1 add: c2];
[compResult print];
NSLog (@”\n”);
[c1 release];
[c2 release];
[compResult release];
// add and print 2 fractions
[f1 print]; NSLog (@” +”); [f2 print];
NSLog (@”----”);
fracResult = [f1 add: f2];
[fracResult print];
[f1 release];
[f2 release];
[fracResult release];
[pool drain];
return 0;
}

both the Fraction and Complex classes contain add: and print methods.
So when executing the message expressions
    Abstraction

qAbstraction is "To represent the essential feature without representing the back ground details.“

qAbstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner.

qAbstraction is the process of hiding the working style of an object, and showing the information of an object in understandable manner.
Method   Overriding
qMethod overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
ex:
// Overriding Methods
#import <Foundation/Foundation.h>
// ClassA declaration and definition
@interface ClassA: NSObject
{
int x;
}
-(void) initVar;
@end
@implementation ClassA
-(void) initVar
{
x = 100;
}
@end
// ClassB declaration and definition
@interface ClassB: ClassA
-(void) initVar;
-(void) printVar; 
NSLog (@”x = %i”, x);}
@end
@implementation ClassB
-(void) initVar // added method
{
x = 200;
}
-(void) printVar
{
NSLog (@”x = %i”, x);
}
@end
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
ClassB *b = [[ClassB alloc] init];
[b initVar]; // uses overriding method in B
[b printVar]; // reveal value of x;
[b release];
[pool drain];
return 0;
}
Object-Oriented Relations

Composition:
q it  gives us a ‘part-of’ relationship.

qMember Object  can’t survive or exist outside the enclosing  or containing class.

Aggregation:
qit gives a ‘has-a’ relationship.

q member Object can’t survives or exist without the enclosing  class.

q it doesnot imply ownerShip,object can exist independently of each other.
Association:
qIt’s  also a relation in which there is no OwnerShip or Container.

qAssociation is a relationship between two objects.association defines multiplicity between objects.
Conclusion
qAn object-oriented approach to application development makes programs more intuitive to design, faster to develop, more amenable to modification, and easier to understand.

qThe Objective-C language is a programming language designed to enable sophisticated object-oriented programming. Objective-C is defined as a small but powerful set of extensions to the standard ANSI C language. Its additions to C are mostly based on Smalltalk, one of the first object-oriented programming languages


........Thank you...........

Tuesday, March 19, 2013

Basic Concept of Objective C and Iphone sdk


Basic Concept of Objective C and Iphone sdk


Objective C Concepts with iPhone


Little about objective C:

Objective-C was created primarily by Brad Cox and Tom Love in the early 1980s at their company Stepstone
Its implementation of an object-oriented extension to the C language. 
Objective-C derives its object syntax from Smalltalk.




What is Class?
Ans.  In Objective-C, we define objects by defining their class. The class definition is a prototype for a kind of object; it declare the instance variable that become part of every member of the class, and it defines a set of methods that can be use by all objects in a class.

What is Object?
Ans. As the name implies that object orient programme based around object. The object associate data with particular operation that that affect or use data.

What is difference between function calls and messages?
 Ans. A function and its argument are joined together at compile time, but a message and a receiving object are united until the programme is running and message is sent.

What is polymorphism?
Ans.  It mean having multiple form. 
  • Polymorphism is the ability to process objects differently depending on their data types.
  • Polymorphism is the ability to redefine methods for derived classes.
There is two types of polymorphism in OOPS:
  1. Compile time
  2. Run Time.
Compile Time: Method overloading, means two same name methods with different argument.

Run Time: Method overriding, means same name, same signature but different implementation.
What is Inheritance?
Ans. Inheritance is a way to reuse of existing code or code of existing objects.
What is NSObject Class?
Ans. NSObjects is root class, that doesn't have any superclass. Its define basic framework of Objective-C and its Objects interaction.
What is Abstract Class?
Ans. Abstract class is a incomplete class, but contains the useful code that reduce the burden of its subclass.

What is Interface and its implementation?
Ans. 
  • An interface that declares the methods and instance variables of the class and names its superclass 
  • An implementation that actually defines the class (contains the code that implements its methods)


    A typical interface and its implementation:
    _____________________________________
    @interface rectangle: Superclass{


    instance variables declaration only....
    .........
    .......
    ........

     }
    method declaration only

    @end


    ______________________________________
    #import "rectangle.h"


    @implementation rectangle
    @synthesize the variable for getter-setter methods


    method definitions


    @end
    _______________________________________

Scope of instance variable in objective c
Some important delegates in iPhone Xcode:
UITableViewDelegate:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView ;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath ;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;





CLLocationManage Delegate:


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;

MKMapView Delegate

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation;

-(void)mapView:(MKMapView *)mapView annotationView:(MKPinAnnotationView*)view calloutAccessoryControlTapped:(UIControl *)control ; 


UIWebView Delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

- (void)webViewDidStartLoad:(UIWebView *)webView;

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


UISearchBar Delegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchB ;

- (void)searchBar:(UISearchBar *)searchB textDidChange:(NSString *)searchText ;

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchB ;

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchB;



UIActionSheet Delegate and UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex ;



MFMailComposeViewControllerDelegate with code:

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayMailComposerSheet 
{
   MFMailComposeViewController *picker = [[[MFMailComposeViewControllerallocinitautorelease]; 
    picker.mailComposeDelegate = self;
   if([MFMailComposeViewController canSendMail])
     {
      [picker setSubject:@"Near2Me iPhone App Feedback"];
       NSString *emailBody =@"";
       [picker setToRecipients:[NSArrayarrayWithObjects:@"xyz444&6@gmail.com",nil]];
       [picker setMessageBody:emailBody isHTML:NO];
       [self.homeView presentModalViewController:picker animated:YES];
       }
}


// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{
// Notifies users about errors associated with the interface
switch (result)
    {
     case MFMailComposeResultCancelled:
     NSLog(@"Result: canceled");
     break;
    case MFMailComposeResultSaved:
    NSLog(@"Result: Saved");
    break;
    case MFMailComposeResultSent:
           if (MFMailComposeResultSent)
           {

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Near2Me Team"
             message:@"Thanks for your feedback. We always try to make application more simpler and            accurate."
            delegate:nil 
           cancelButtonTitle:@"OK" 
           otherButtonTitles:nil];
           [alert show];
           [alert release];
            }
    NSLog(@"Result: Sent");
   break;
   case MFMailComposeResultFailed:
   NSLog(@"Result: failed");
   break;
   default:
   NSLog(@"Result: not Send");
   break;
   }
[self.homeView dismissModalViewControllerAnimated:YES];
//[appDeleg.window addSubview:appDeleg.viewMenuTab];
}







UINavigationController
homeView = [[HomeViewController alloc]initWithNibName:@"HomeViewController"bundle:[NSBundle mainBundle]];


navigation = [[UINavigationController alloc]initWithRootViewController:homeView];

[self.window setBackgroundColor:BGCOLOR];

[self.window addSubview:navigation.view];



// hiding - show navigationController setToolbar

    [self.navigationController setToolbarHidden:YES animated:NO];





UITabBarController



 self.window = [[[UIWindow allocinitWithFrame:[[UIScreen mainScreenbounds]]autorelease];
UIViewController *viewController1 = [[[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nilautorelease];

UIViewController *viewController2 = [[[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nilautorelease];

tabBarController = [[[UITabBarController allocinitautorelease];
tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];

self.window.rootViewController = self.tabBarController;






NSXMLParser


Parsing the start of an element
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict ;


Parsing an element’s value

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

Parsing the end of an element//XMLParser.m
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {






UIPickerView Delegates


- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
 
return [arrayColors count];
}

- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [arrayColors objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
 
NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row);
}