Showing posts with label XCode for IPhone. Show all posts
Showing posts with label XCode for IPhone. Show all posts

Thursday, March 1, 2012

Objective-C basic - [import from library and user created file]

Now we will discuss about objective –c in more details.  If we will see a code in objective-c ,at the top , then we will get import key word followed by file names. Here we may find two different pattern of declaration.
#import <someFileName.h>
And
#import “someFileName.h”      
What is the difference between these?
Nothing tough, first one is for a header file from library folder and second one is for a header file from application folder itself.
Very easy, right?
Example-
#import <foundation/foundation.h> //import foundation header file from library
#import “myHeader.h” //import myHeader.h file from my project/app folder.
That’s it. See you in next post.

Sunday, January 15, 2012

What is MVC? How it is implemented in iPhone development?


MVC, a much known term in software industry right now.  I will not spend much time to explain MVC; rather, how it is implemented in IPhone will get more priority in this article. Let’s start.
MVC - simply Model View Controller.
Now take a simple example. Suppose a car. It has a body, four wheels, one steering and one engine. Now, engine is a module, steering is a controller, wheel is a separate module and guess what, body is view. Pretty simple, right. Now come out from the car. In software, an object which represents project entities is module. Controller will do various operations with modules depending on different commands and commands will be sending user interface [view] and the output result will be shown in view itself.
It’s done.
mvc iphone
MVC Architecture 



Cocoatouch is a building block of iPhone development. It is solely following MVC for development. As we understood previously, it has model, view and controller, iPhone development follows the same.  When we create an application using xCode, it will give us a specific folder structure with the support of MVC itself. In the folder one can see view and viewController files.  There will be two kinds of file or rather we can say same named files with two different extensions [*.h , *.m].



Now, let’s see ,what is in it.
[.H] file will contain something like ----

@interface MainViewController : UIViewController {
UILabel *label;// label is added to it
}

@property (nonatomic, retain) IBOutlet UILabel *label;
 //will be used as a reference to controller
@end

Here we can see, it is an interface which inherits UIViewController[Master class for all view]. It also contains a label[Added by us].

[.m]file will contain ---
#import "MainViewController.h"
#import "MainView.h"

@implementation MainViewController
@synthesize label; //to do sync properties in interface

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}

- (void)dealloc {
[label release];
[super dealloc];
}

@end

Here, we implement the created interface in .H file as far as MVC concerns.  And it will work with all the properties declared in interface. Here we use @synthesize to synchronize attributes in [.m] and [.h].
Now in this way we created a controller and an interface for view. Sounds confusing?  Yes , View.h file will work as an interface for view [normal MVC concept].  
We will have .xib files too. It is basically an xml which represents the actual UI.

Now , from the toolbox we can get all available controls ,which we can drag and drop to the UI to design as per our requirement. [The process of designing will not be here in this article. It’s all about MVC in iPhone]
Now it is the time to connect the UI to View to interact with controller.


In view controller connection window, we can find all the added controls in a list. By dragging the listed control reference to the View object cube we can map the UI objects to view properties. All the code related to it will be auto generated. So in this way view and controller will be connected.
Now, we can create a custom model to interact with values sent from view. To do that we need to create an interface of a model in myCar.h file-
#import <foundation/Foundation.h>

@interface myCar : NSObject {
    NSString *name;
}

@property (nonatomic, retain) NSString *name;

+ (myCar *)sharedModel;

@end

Now we are ready to implement the interface in myCar.m file.
#import "myCar.h" 
@implementation myCar \\    here the implementation
@synthesize name;\\ synthesize with interface implementation

- (id) init
{
    self = [super init];
    if (self != nil) {
        name = @"";
    }
    return self;
} 
- (void) dealloc
{
    [name release]; \\release memory from device
    [super dealloc];
}
 @end
Our model is also created.  It’s the time to implement model in our code. See bellow-
- (IBAction)textChanged:(id)sender
{
    myCar *car = [myCar sharedModel];
    model.text = textField.text;
}

It is just an over view. Explore much by creating an app.
Enjoy

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)
{
        printf("Hello!");
        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
{
        called();
}
int main(void)
{
        caller();
        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----
@interface
used to declare of class or interface.
@implementation
used to define a class or category.
@protocol
used to declare a formal protocol.
@end
ends the declaration, definition, category or protocol.
@private
Limits the scope of an instance variable to the class that declares it.
@protected
Limits instance variable scope to declaring and inheriting classes.
@public
Removes restrictions on the scope of instance variables.
@try
Defines a block within which exceptions can be thrown.
@throw
Throws an exception object.
@catch
Catches an exception thrown within the preceding @try block.
@finally
A block of code that is executed whether exceptions were thrown or not in a @try block.
@class
Declares the names of classes defined elsewhere.
@selector(method_name)
It returns the compiled selector that identifies method_name.
@protocol(protocol_name)
Returns the protocol_name protocol (an instance of the Protocol class). (@protocol is also valid without (protocol_name) for forward
declarations.)
@encode(type_spec)
Yields a character string that encodes the type structure of type_spec.
@"string"
Defines a constant NSString object in the current module and
initializes the object with the specified 7-bit ASCII-encoded string.
@synchronized()
Defines a block of code that must be executed only by one thread
at a time.
bool
It takes YES /NO
'self'

‘Super’



Example code –

#include <objc/Object.h>
 
@interface Car:Object
{
  //For instance variables 
}
 
- (void)company;
 
@end
 
#include <stdio.h>
 
@implementation Car
 
- (void)company
{
        printf("BMW!\n");
}
 
@end
 
#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]])
 yourFunction();
Or,
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;
}

@end

In  iWebServiceViewController.m ->
//======User Defined==============
-(void)connectService{
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