Showing posts with label Beginning iPhone development. Show all posts
Showing posts with label Beginning iPhone development. Show all posts

Friday, July 9, 2010

Using Interface Builder to connect Outlets/Actions - Easy Loan Calculator Part 3

Essentially, we have implemented all the codes. In summary, we have declared Outlets which are references to our UIControls and Actions, which are events which we be triggered when we click on buttons.

Now we need to link the Outlets to the UIControls that we have designed in our xib file. 
Apple enforces a View-Controller-Model. Which is essentially keeping the UI layer and the business logic layer separate. Advantages are that we can change either layer without affecting much the other layer. i.e. if i were to change my UI drastically, my business logic layer can still link to the new UI with some re-linking.

Now it is this linking that we are going to do now. Linking the text boxes and labels to the Outlets we have declared earlier. (They are called IBOutlet because IB - Interface Builder)

In Interface Builder, you have these window with three icons in it. The view icon just opens your View. Ignore First Responder for now. 

Click on File's owner. Press and hold the Control key. Mouse click from File's owner to over the textbox. You should see a black box with drop down values of all the Outlets of textbox type that you have declared earlier.  See below. Click on the Outlet which should correspond to that textbox. You have just linked your Outlet to the textbox.


Continue for the rest of the text boxes and labels. Having done that, we now proceed to link the button to the Action that we have implemented. i.e. link the Calculate button to the Calculate method.

Click on the button. Press and hold the Control key, and drag and hold to File's Owner. A black box with drop down values of the Events should appear. Select the correct event. In this case, we select the btnCalculate action.
You can think of Events or Actions as the same thing. 





There you go, your Outlets and Actions are all properly linked. Just ensure that you save all your files with command-S. Build and Run with command-R and the iPhone simulator should appear with your loan application. =)




So you learned the important lesson of Outlets and Actions through this exercise. Essentially, its all about receiving/sending user input (Outlets), and event handling with buttons (Actions).

With this, you can go on and build many many other applications.

Now as you test your application, a terrible thing happens. Your keyboard does not go away! Shocking! isn't this intuitive that the keyboard should go away? How do we make it go away?

We will touch on that in the next article.

Objective C - Convert string to double and double to string Part 2 - Filler


Before we go on to part 3, let me stop to pause for an important part of the code and zoom in a little more. For in the code, we have done something important, converting double into a string, and string into a double.

Now i initially thought that a simple google search would return me the result but to my horror...it doesn't! Especially for the double to format to 2 dp and become a string.

So here goes...

double loanAmount = [tbxLoanAmount.text doubleValue];

Remember the above code? Its to the equivalent of double d = Convert.ToDouble(tbx.Text) in C#. Over here, we are calling the doubleValue method of the String (or rather NSString - NS = NextStep) class to convert the text box Text property into a double.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter allocinit];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
We now create the NumberFormatter object. Again its prefixxed with NS - NextStep. This object will format our 1.234566 into a nice 1.23 format. Of course you can format to percentages as well. There are also other formatters like date formatters.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter allocinit];

We create the NumberFormatter object here. In short, we are doing a NumberFormatter nf = new NumberFormatter() here. [NSNumberFormatter alloc] is for allocating memory to hold this object. init - initialization. You will see [[Object alloc] init] very frequently.

NSNumber *n1 = [NSNumber numberWithDouble:paymentAmt];

Next, convert the double into a NSNumber type with the above code. Again, in C#, it will be NSNumber n1 = NSNumber.numberWithDouble(payment); Yea, its a static method.



 NSString *paymentAmtString = [numberFormatter stringFromNumber:n1];
Finally, using the numberFormatter object, which takes in a NSNumber argument, we finally convert our double to a String. Which we can assign to a text box Text property as per below.

monthlyPayment.text = paymentAmtString;

So in summary, double -> NSNumber -> NSNumberFormatter -> NSString.

Unbelieveable right, the amount of work you need to convert a formatted double into a String.
Yea, still more unbelievable things to come.

Outlets and Actions - Easy Loan Calculator Part 2

Ok, let's go on to implement the codes, the nuts and bolts of the calculator. In summary, we have to drag drop labels, textboxes to receive user input, some buttons to trigger the execution of the program, code the formula for the loan, and out put the result to labels again. Let's begin.

Under Resources, click on EasyLoanCalculatorViewController.xib file to open Interface Builder.
You will see a blank view. From the Library window, (you can open the Library from Tools -> Library) you can select your UI controls to the view. Its essentially like toolbox in visual studio.

So carry on and design your UI till it resembles something like the below. Ignore the picture of the percetage sign at the end.


In the process, you would have dragged and dropped several labels, text boxes, and buttons.

Next, let's type out the code for the EasyLoanCalculatorViewController.h file. The code is listed below.




#import

@interface EasyLoanCalculatorViewController : UIViewController {
IBOutlet UITextField *tbxLoanAmount;
IBOutlet UITextField *annualInterestRate;
IBOutlet UITextField *noOfYears;
IBOutlet UILabel *monthlyPayment;
IBOutlet UILabel *totalInterest;
IBOutlet UILabel *totalPayment;
}

@property (nonatomic,retain) UITextField *tbxLoanAmount;
@property (nonatomic,retain) UITextField *annualInterestRate;
@property (nonatomic,retain) UITextField *noOfYears;
@property (nonatomic,retain) UILabel *monthlyPayment;
@property (nonatomic,retain) UILabel *totalInterest;
@property (nonatomic,retain) UILabel *totalPayment;


-(IBAction) bgTouched:(id) sender;
-(IBAction) btnCalculate:(id) sender;

@end



Explanation of the codes. 

#import 

Import the UIKit framework. There are many other frameworks you can import like the Accelerometer, the MapKit and many others which we will go through in future tutorials.

@interface EasyLoanCalculator3ViewController : UIViewController {

Declare an interface EasyLoanCalculator3ViewController that inherits from UIViewController.





IBOutlet UITextField *tbxLoanAmount;
IBOutlet UITextField *annualInterestRate;
IBOutlet UITextField *noOfYears;
IBOutlet UILabel *monthlyPayment;
IBOutlet UILabel *totalInterest;
IBOutlet UILabel *totalPayment;
}


Declare the UIControls that you are to use in the xib file. These are what we have dragged and dropped previously. These are also called Outlets. Outlets are declarations of UIControls where we take in or out put data from/to user. Btw, you need to declare these variables with a * which means that there are object references. Don't understand? Just do it first. Will slowing understand later.

@property (nonatomic,retain) UITextField *tbxLoanAmount;
@property (nonatomic,retain) UITextField *annualInterestRate;
@property (nonatomic,retain) UITextField *noOfYears;
@property (nonatomic,retain) UILabel *monthlyPayment;
@property (nonatomic,retain) UILabel *totalInterest;
@property (nonatomic,retain) UILabel *totalPayment;

Set these UIControls as properties. Nonatomic refers to that there can be multiple threads running at the same time. 

-(IBAction) bgTouched:(id) sender;
-(IBAction) btnCalculate:(id) sender;

These are Actions. Typically, we use buttons to activate actions. We have to code these actions later on in the .m file. Here we have two actions. Just concentrate on btnCalculate for now. It is used for the calculation of the loan formula later on.

@end

I won't even comment on this. Next up, the .m file. Find the code below.





#import "EasyLoanCalculatorViewController.h"

@implementation EasyLoanCalculator3ViewController

@synthesize tbxLoanAmount;
@synthesize annualInterestRate;
@synthesize noOfYears;
@synthesize monthlyPayment;
@synthesize totalInterest;
@synthesize totalPayment;

-(IBAction) bgTouched:(id) sender{
[tbxLoanAmount resignFirstResponder];
[annualInterestRate resignFirstResponder];
[noOfYears resignFirstResponder];
}

-(IBAction) btnCalculate:(id) sender{
double loanAmount = [tbxLoanAmount.text doubleValue];
double intRate = [annualInterestRate.text doubleValue];
double years = [noOfYears.text doubleValue];
double r = intRate/1200; // to optimize to handle different payment periods
double n = years * 12;
double rPower = pow(1+r,n);
double paymentAmt = loanAmount * r * rPower / (rPower - 1);
double totalPaymentd = paymentAmt * n; 
double totalInterestd = totalPaymentd - loanAmount; 
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSNumber *n1 = [NSNumber numberWithDouble:paymentAmt];
NSNumber *n2 = [NSNumber numberWithDouble:totalPaymentd];
NSNumber *n3 = [NSNumber numberWithDouble:totalInterestd];
NSString *paymentAmtString = [numberFormatter stringFromNumber:n1];
monthlyPayment.text = paymentAmtString;
NSString *totalInterestString =[numberFormatter stringFromNumber:n3];
totalInterest.text = totalInterestString;
NSString *totalPaymentString =[numberFormatter stringFromNumber:n2];
totalPayment.text = totalPaymentString;
}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}


- (void)dealloc {
[tbxLoanAmount release];
[annualInterestRate release];
[noOfYears release];
[monthlyPayment release];
[totalInterest release];
[totalPayment release];
    [super dealloc];
}

@end


Explanation






#import "EasyLoanCalculatorViewController.h"

Import the header file which we have just coded.

@implementation EasyLoanCalculatorViewController

@synthesize tbxLoanAmount;
@synthesize annualInterestRate;
@synthesize noOfYears;
@synthesize monthlyPayment;
@synthesize totalInterest;
@synthesize totalPayment;

The synthesize keyword just means generating the getter and setter methods for each of the UIControls which we have declared in the .h file.

-(IBAction) bgTouched:(id) sender{
[tbxLoanAmount resignFirstResponder];
[annualInterestRate resignFirstResponder];
[noOfYears resignFirstResponder];
}

This is the first Action we have declared earlier in the .h file. Ignore this for now.

-(IBAction) btnCalculate:(id) sender{

Start to implement the btnCalculate Action. Its essentially a method. We name the method btnCalculate that takes an argument of id type and call it sender.
double loanAmount = [tbxLoanAmount.text doubleValue];
double intRate = [annualInterestRate.text doubleValue];
double years = [noOfYears.text doubleValue];

Declare some double variables, and assign the value of the text property of the Textbox. i.e. what the user typed in. Before assigning it, change it to a double type. [tbxLoanAmount.text doubleValue] is essentially tbxLoanAmount.text.ConvertToDouble(); 

To generalize, obj.method() in objective c is [obj method];
double r = intRate/1200// to optimize to handle different payment periods
double n = years * 12;
double rPower = pow(1+r,n);
double paymentAmt = loanAmount * r * rPower / (rPower - 1);
double totalPaymentd = paymentAmt * n; 
double totalInterestd = totalPaymentd - loanAmount; 

Above should be reasonably understood unless you have never coded before. Perhaps what is more difficult to understand who be the formula itself. But you worry about it, you can change the formula to what you want, its just a financial formula which can be readily changed to anything formula you want.
NSNumberFormatter *numberFormatter = [[NSNumberFormatter allocinit];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];

NSNumber *n1 = [NSNumber numberWithDouble:paymentAmt];
NSNumber *n2 = [NSNumber numberWithDouble:totalPaymentd];
NSNumber *n3 = [NSNumber numberWithDouble:totalInterestd];

NSString *paymentAmtString = [numberFormatter stringFromNumber:n1];
monthlyPayment.text = paymentAmtString;
NSString *totalInterestString =[numberFormatter stringFromNumber:n3];
totalInterest.text = totalInterestString;
NSString *totalPaymentString =[numberFormatter stringFromNumber:n2];
totalPayment.text = totalPaymentString;
Will discuss the above in depth in a separate article. Essentially, its creating the Formatter object to format a double to 2 decimal places. And converting the double values into a string to assign them to the labels.text property. So, out the calculated results to the labels - monthly payment, total interest and total payment.

}

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

Certain events that the program throws. But we do not have to handle them for the moment.


- (void)dealloc {
[tbxLoanAmount release];
[annualInterestRate release];
[noOfYears release];
[monthlyPayment release];
[totalInterest release];
[totalPayment release];
    [super dealloc];
}

Called when the program exits, release all my objects used for the UIControls.

@end

Await Part 3 where we will link the Outlets to the UIControls and buttons to the Actions.
And of course, build and run the app.

Tuesday, July 6, 2010

Introduction to Xcode - Easy Loan Calculator Part 1

Ok. Finally, let's get down to writing some decent code. Let's skip the HelloWorld example and code something that perhaps we can probably get some hits in appstore. See below for the finished product.
Its a loan calculator, where you fill in the loan amount, the interest rate, and the no. of years of the loan.
The app then calculates the monthly payment that you ought to pay, calculates the total interest paid throughout the loan and the total amount paid.


First off, open xcode and create a View based project.
Name it EasyLoanCalculator.

You should see the above screen.
Left pane: shows all your files in a similar fashion to your solution explorer in Visual Studio (VS).
Right pane shows the individual files selected in the folder and the code in the lower right.

You have a couple of folders. More important ones for now are the 'classes' folder and the 'resources' folder. The classes folder basically contains your source code files. Resources folder contains your UI files, i.e. Forms in VS.

For this first app, you just to write code in EasyLoanCalculatorViewController.h and EasyLoanCalculatorViewController.m. The .h file is the header file where you write all your declarations. Including declarations for UI Controls like labels, textboxes. The .m file is where all code is.

In 'resources', you see EasyLoanCalculatorViewController.xlb which is your Interface Builder file. You know, the one where you drag and drop UI controls in like for forms in VS. Click on it and Interface Builder (think VS only in design view) opens with a blank iPhone screen.

That's all for introductions and orientations. Await part 2 for actual programming.

Sunday, July 4, 2010

Should I get a apple license?

What is the apple license good for? It costs almost S$150 PER year. Now that's alot of money especially for students. Definitely we should not be just blindly signing up with an account if we do not know the use of it.

Let's go through the uses of it.

1. It allows you to upload your app on to appstore. Yes, and that's the main point of it. Do however note that for your app to be downloadable, you need a current valid license. That is to say, if you have submitted an app onto app store, and your apple license has expired, your application WILL NOT be downloadable.

2. It allows you to deploy your code onto a device. i.e. iphone/pad/pod. That's quite a shocker for me originally. But yea, Apple controls their stuff tightly.
Sure you can run your apps on the simulator, but you will be restricted to CRUD kind of apps, since you have no access to the accelerometer, GPS and bluetooth functions in the iPhone.
So if you are looking at using maps, playing balancing games, and chatting via bluetooth, its quite necessary to get the license.

Of coz, teams can use a 'Shared' license. But do need that each license can only deploy up to a 100 devices. So do not misuse it by sharing it with too many friends.

Jason

First steps to iphone development.

First things to iphone/iPad development.

You need a MAC. I personally think that macbook is good enough for development. But of course if you don't mind spending some additional dollars, you can get the macbook pro.

There is a good educational offer for students, staffs in schools, and also for parents of students. Go to www.apple.com.sg where there is currently an offer for a macbook/pro at a discounted price, + free iPod touch, + free printer (S$199). Quite a good offer if you have the budget.

Second thing, once you have the mac. Get a apple developer id at developer.apple.com and you can download the iPhone SDK 4.0. It will come along with it xcode, the IDE for objective c, and Interface Builder, where you design the UI for the iPhone/iPad apps.

Note that apple appstore now only restricts apps developed in iPhone SDK 4.0 to be submitted to app store.

Third thing, is BOOKMARK this site! Look out for updates.

Welcome to easyiphoneapp site!

Welcome welcome. To get straight to the point, this blog will record my experiences in learning iphone programming which i hope will be beneficial to those who are interested in iphone programming as well.

There is a serious lack of good iphone programming tutorials and i hope that this blog can prove to contribute EASY to follow, yet DEEP iphone programming content.

I hope my articles will be in plain english, that anyone which some basic programming background can follow and code his or her own app.

So await for more exciting articles, as i chart our iphone development journey!

Jason