Tuesday, December 27, 2011

Objective-C basic

Objective C
This is a primitive language used in Apple device application development (IOS/Macintosh). The base of this language is c. Objective –C is an easy to understand and object oriented programming language.  Objective – c comes with library, development tool and OOPs.
The basic 3 parts are-
1. inter- face
  Signature class. [*.h file]
2. implementation
Definition of a class.[*.m file]
3. Instantiation
instantiation of class by allocating memory.
It is a dynamic language. It supports open dynamic binding to create easy architecture for user interface.
Basic structure of a program-
#include <stdio.h>
//----Header file added------
int main(void)
        return ;
//----------Body Ends-----

Code file extension will be “.m”. It complies line by line. So if we need to call a function in other function, caller function should be bellow of called function.
#include <stdio.h>
-(void) called
-(void) caller
int main(void)
        return ;

For MAC ,Object compilation –
$ gcc -o hello hello.m \ -L /System/Library/Frameworks/Foundation.framework/Foundation
Run compiled code on MAC
$ ./hello
Compiler for Objective – c can be downloaded from - http://www.gnustep.org/experience/Windows.html. [For windows]

 Key Words----
used to declare of class or interface.
used to define a class or category.
used to declare a formal protocol.
ends the declaration, definition, category or protocol.
Limits the scope of an instance variable to the class that declares it.
Limits instance variable scope to declaring and inheriting classes.
Removes restrictions on the scope of instance variables.
Defines a block within which exceptions can be thrown.
Throws an exception object.
Catches an exception thrown within the preceding @try block.
A block of code that is executed whether exceptions were thrown or not in a @try block.
Declares the names of classes defined elsewhere.
It returns the compiled selector that identifies method_name.
Returns the protocol_name protocol (an instance of the Protocol class). (@protocol is also valid without (protocol_name) for forward
Yields a character string that encodes the type structure of type_spec.
Defines a constant NSString object in the current module and
initializes the object with the specified 7-bit ASCII-encoded string.
Defines a block of code that must be executed only by one thread
at a time.
It takes YES /NO


Example code –

#include <objc/Object.h>
@interface Car:Object
  //For instance variables 
- (void)company;
#include <stdio.h>
@implementation Car
- (void)company
#include <stdlib.h>
int main(void)
        id myCar;
        myCar =[Car new];
        [myCar company];
        [myCar free];
        return EXIT_SUCCESS;

Monday, December 26, 2011

Comparing NSString AND NSNumber in XCode

For the beginners, it is a bit uncommon string comparing syntax. I faced the same problem at the beginning of iPhone programming. It is not complex but jut you have to know the syntax, that’s it.
Get the string from a nsdata type and compare it with other string.
NSString comparison--
 NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSString *txtComp = @"Value1";
if ([txt isEqualToString:txtComp]) {
lblVal.text = txt;
Note: [The “==” operator will compare the reference to your string literal and so never return true.]
Now, to compare NSNumeric -
if([numValue isEqualToNumber:[NSNumber numberWithInt:7]])
If([myNumber intValue] == 7)
Now , compare String with Number-
Just convert Number to string and do compare.

Convert NSString to and from NSNumber in XCode-

Convert String to Number in XCode-
Variable declare-
NSNumberFormatter * numValue = [[NSNumberFormatter alloc] init];
Set the number variable to contain Decimal value.
[numValue setNumberStyle:NSNumberFormatterDecimalStyle];
Get the string value from string-
NSNumber * myNumber = [numValue numberFromString:@"7"];
Release memory-
[myNumber release];
Convert Number to String in XCode-
NSString *myStr = [NSString stringWithFormat:@"%d",intValueHere];

That’s it  Enjoy J

Thursday, December 22, 2011

iPhone with WebService

Here, we can find how to connect a web-service in iPhone application to view list.
I assume that a web service is already created in Asp.net or Jsp or PhP which return data in json format. Now, we have three things to do, to connect the web service. 1> Connect web service; 2> Access data from it and 3> Show it in a list.
First click on xCode icon. It will open the xCode tool.

Now, select option to create new project. Choose view base application from the list. 

Give a name for the project and we are ready to go now.

There will be few files in project. Some of them are not require any changes. Delete -  ViewController.h and ViewController.m  and then add file from File->New File .

Then Select UIViewController type and do next.

Select UITableViewController and give name iWebServiceViewController and save.  The files with which we will work are-  iWebServiceViewController.h and iWebServiceViewController.m  from Classes folder .  ‘.H’ -file contains a kind of signature of ‘.M’ file.  Another one is - iWebServiceViewController.xib in Resources folder under project. It will be used for design the application window.

1>Connect web service[ using Object-C]
In  iWebServiceViewController.h ->
#import <UIKit/UIKit.h>
#define wsURL @"http://yourwebserviceurl"
@interface listEmpViewController : UITableViewController {
NSMutableArray *jsonResult;


In  iWebServiceViewController.m ->
//======User Defined==============
NSURL *url=[NSURL URLWithString:wsURL];
NSData *data=[NSData dataWithContentsOfURL:url];
[self getData:data];
In viewDidLoad method->
- (void)viewDidLoad {
            [super viewDidLoad];
[self connectService];

2> Access data from it->
-(void)getData:(NSData *) data{
            NSError *error;
            jsonResult = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

3> Show it in a list ->

In  iWebServiceViewController.m ->

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [jsonResult count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSDictionary *info= [json objectAtIndex:indexPath.row];
cell.textLabel.text=[info objectForKey:@"forename"];
    return cell;

At last-
In AppDelegate.m changes need to be done in import->
#import “iWebServiceViewController.h”
And also in didFinishLaunchingWithOptions->
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    // Override point for customization after application launch.
iWebServiceViewController *listEmp=[[ iWebServiceViewController alloc] init];
listEmp.title=@"Emp table";
self.window.rootViewController= listEmp;
// Set the view controller as the window's root view controller and display.
            //self.window.rootViewController = self.viewController;
            [self.window makeKeyAndVisible];
            return YES;

That’s it, Enjoy… J