<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jayway Team Blog &#187; Christian Hedin</title>
	<atom:link href="http://blog.jayway.com/author/christianhedin/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jayway.com</link>
	<description>Sharing Experience</description>
	<lastBuildDate>Tue, 20 Jul 2010 08:26:15 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Continuos Integration for XCode projects</title>
		<link>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/</link>
		<comments>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 17:35:59 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[hudson]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4624</guid>
		<description><![CDATA[Continuos Integration is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://martinfowler.com/articles/continuousIntegration.html" title="Continuous Integration">Continuos Integration</a> is the practice of integrating changes from many people as often as possible. Instead of merging changes once a month and spending time handling merge errors you try integrate every day, perhaps even every hour. Each integration is built and tested on a server. If there are build errors or test failures, you and your team will be notified right away.
</p>
<p>
This is the second part of the blog post I wrote about <a href="http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/">TDD in XCode</a>. Make sure you've followed that tutorial before continuing here, or at least have a project of your own with OCUnit tests ready.
</p>
<p>
The server which we'll use is called <a href="https://hudson.dev.java.net/" title="Hudson">Hudson</a> and is very popular in the Java community. It does not readily support XCode projects but it does allow shell commands, so we'll use that to make our Calculator project compatible. We also want to fetch new versions of the source code as soon as it's checked in. We'll be a bit fancy and use <a href="http://git-scm.com/" title="Git - Fast Version Control System">Git</a> as source control software.	Here's a summary of what we want to do:
</p>
<ol>
<li>Download and install the Hudson continuos integration server</li>
<li>Download, install and setup the Git source control software as well as the Git plugin for Hudson</li>
<li>Download and install a script that converts OCUnit test results to JUnit format</li>
<li>Setup a new job in Hudson that checks out our XCode project and builds and tests it</li>
<li>Set up a notification and try it out</li>
</ol>
<h2>Downloading and Installing Hudson</h2>
<p>
In order to keep the instructions in this tutorial simple, we will have the source code repository and the build server itself on localhost. In real life you'll probably want to setup a dedicated machine.</p>
<p>Head over to the <a href="https://hudson.dev.java.net/" title="Hudson">Hudson web site</a> and download your copy of the server. Follow their included installation instructions, it's quite simple. Once you have Hudson up and running you can visit <a href="http://localhots:8080">http://localhost:8080</a> to see the welcome screen. By the way, when you're ready to install Hudson on a real remote server I recommend running it as a Servlet inside <a href="http://tomcat.apache.org/" title="Apache Tomcat - Welcome!">Apache Tomcat</a> instead.
</p>
<h2>Downloading and Setting Up Git</h2>
<p>Next we want to install Git. There are several ways to install it. The simplest might be to use <a href="http://code.google.com/p/git-osx-installer/">the OS X installer</a>, but I personally prefer <a href="http://www.macports.org/" title="The MacPorts Project">MacPorts</a>. Either way, go ahead and install it and make sure that you can use the "git" command from Terminal.app when you're done.
</p>
<p>
In the Terminal, change directory to your XCode project folder and type:</p>
<pre class="brush:bash">
		git init
	</pre>
<p>You now have a working source code repository in your project folder. Neat. Before you continue create a text file called <em>.gitignore</em> and let it contain:</p>
<pre class="brush:plain">
		build/*
		*.pbxuser
		*.mode1v3
		.DS_Store
		test-reports/*
	</pre>
<p>	That's a listing of the files and folders that should not be version controlled, since they are temporary or just used for XCode. Feel free to add any other files that you think only should be present locally. Now add all files (that aren't ignored) using:</p>
<pre class="brush:bash">
		git add *
	</pre>
<p>	and finally commit them to a first version using:</p>
<pre class="brush:bash">
		git commit -m "Initial import"
	</pre>
</p>
<h2>Fetching the Script</h2>
<p>
We need to fetch one more thing, <a href="http://github.com/ciryon/OCUnit2JUnit/blob/master/ocunit2junit.rb">ocunit2junit.rb</a>, which is a little Ruby script that I wrote. Since you now have git, you can also download it using git (or <em>clone the repo</em>, which is the correct term). Change directory to /tmp and then type like this:</p>
<pre class="brush:bash">git clone git://github.com/ciryon/OCUnit2JUnit.git</pre>
<p>Copy the script from /tmp/OCUnit2JUnit/ anywhere, like to /usr/local/bin/. Make sure it's executable by typing <em>chmod +x ocunit2junit.rb</em>.</p>
<p>The script will parse output from xcodebuild (the console command for building your XCode project) and look for output from OCUnit. The test results (success, failure, time passed etc) will be saved in the "test-reports" folder in the same XML format that JUnit uses. This also happens to be a format that Hudson understands.
</p>
<h2>Setting Up Hudson</h2>
<p>
Now head back to your Hudson welcome screen. Select <em>Manage Hudson</em>, <em>Manage plugins</em> and check "Hudson GIT plugin" under <em>Available</em>. Hudson will automatically download and install the plugin. Afterwards just restart Hudson.
</p>
<p>
We're ready to create a job in Hudson for our project. From the main screen select "New job", Build a free-style software project and call it "Calculator". There are some settings which you should fill in:</p>
<ul>
<li>
			Select to use git as source code management tool. The URL should be the file path to your project, like:
<pre class="brush:bash">/Users/youruser/XCodeProjects/Calculator/</pre>
</li>
<li>
			Select to poll SCM with Schedule:
<pre class="brush:bash">* * * * *</pre>
<p>			That means it'll check every minute if there are changes. If you want to check less often, do that.
		</li>
<li>
			Add new build step and select to execute shell. Use this command (make sure to point to the version of the iPhone SDK you want to use):</p>
<pre class="brush:plain">xcodebuild -target "UnitTests" -sdk /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.1.2.sdk/ -configuration "Debug" | /usr/local/bin/ocunit2junit.rb</pre>
</li>
<li>
			Select to also publish a JUnit test result report and the Test report XMLs reside at
<pre class="brush:plain">test-reports/*.xml</pre>
</li>
</ul>
<h2>Trying it out</h2>
<p>This is the moment of truth. Try to change your CalculatorTest.m so that one of the test cases fail. Type:</p>
<pre class="brush:bash">
	git -a commit CalculatorTest.m "Broke the test, on purpose"
</pre>
<p>and see what happens. If all goes well, and you have entered everything correctly,  Hudson should automatically notice there's a new version available, build it and try to run the test suite. Check the results and how it reports the test failure. Nice, eh? Fix the error and commit the test class again to see how Hudson reacts.
</p>
<p>
There are many settings, plugins and cool things to try out in Hudson. Go into Manage Hudson-> Configure system and setup your email settings, to allow Hudson to send mail. Then go back to configure your Calculator job and at the bottom select E-mail Notification. Enter your own email address and see how it works after you commits a file that breaks the build. If you don't want a mail, you can get an instant message, or perhaps have the server play a loud annoying sound? Everyone in your team should be aware of when a build fails, so it can be fixed right away. This is one of the great advantages of having a continuos integration server.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/31/continuos-integration-for-xcode-projects/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Test Driven Development in XCode</title>
		<link>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/</link>
		<comments>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 08:35:26 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[tools]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=4301</guid>
		<description><![CDATA[Test Driven Development, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the Three Rules of TDD that dictate the following: You are not allowed to write any production code unless it is to make a failing [...]]]></description>
			<content:encoded><![CDATA[<p>
        <a href="http://en.wikipedia.org/wiki/Test-driven_development" title="Test-driven development - Wikipedia, the free encyclopedia">Test Driven Development</a>, or TDD for short, is a simple software development practice where unit tests, small focused test cases, drive the development forward. This is most easily explained by the <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd" title="TheThreeRulesOfTdd">Three Rules of TDD</a> that dictate the following:</p>
<ol>
<li>You are not allowed to write any production code unless it is to make a failing unit test pass.</li>
<li>You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.</li>
<li>You are not allowed to write any more production code than is sufficient to pass the one failing unit test.</li>
</ol>
<p>That means that test cases are written before any production code. Not all tests are written up front, it's rather that a small test is written, then a small piece of production code is written that only allows that test to pass. This is repeated in <a href="http://www.agiledata.org/essays/tdd.html">many small iterations</a>: test, fail, code, pass, test, fail, code, pass...<br/><br />
Many people consider TDD to encourage clean code, simple architectures and a stable system that's actually testable. Plus, it's also fun! We've <a href="/tag/tdd/">previously written</a> about various aspects of TDD, but in this tutorial we'll focus on how it works for XCode projects, where you write apps for Mac and iPhone. We will create a simple XCode project, do some special configuration steps and then demonstrate how TDD can be used to write your app. We're going to use <a href="http://www.sente.ch/software/ocunit/">OCUnit</a> and its framework SenTestingKit, which nowadays is included with Apple's XCode tools.
</p>
<h2>Creating the Calculator project</h2>
<p>
Let's start by creating a new project in XCode. You can pick any template, since we aren't going to touch the generated code. I picked a Window-based iPhone project. Name the project <em>Calculator</em>. Select New Target from the Project menu. Under Cocoa select Unit test Bundle. Call it <em>UnitTests</em> (I've had problems with space in the target name so avoid that) and add it to the project. We now need to change some small settings for this target. Select the UnitTests target and hit Command-I for Info. Select the Build tab and locate <em>Other Linker Flags</em>. Replace <em>Cocoa</em> with <em>Foundation</em>. Also remove the entry for <em>GCC_PREFIX_HEADER</em>.
</p>
<p>
Now it's time to create your test suite. Create a new group in your project and call it "Test Classes". Add a new File to this group and make sure it's a Cocoa->Objective-C test case class. Name it <em>CalculatorTest.m</em>. Uncheck "Also create CalculatorTest.h" since we don't need a header file. Don't add it to the Calculator target, but check it to be included in UnitTests. Open CalculatorTest.m file and above the @implementation declaration add:</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{

}
@end</pre>
<p>This is just because we don't want a rather empty header file. All your test classes will look like this.</p>
<p>Following TDD, we should build right away.  First make sure that the active target is "UnitTets" and then press the "Build" button. This will not only do a normal build, but also perform some shell script magic and actually execute the  unit tests. Now the build fails of course, since Calculator.h can't be found.</p>
<p>So let's add a file which represents production code. Create a new empty Cocoa Touch Objective-C class called Calculator.m (also create the .h file), this is the class that we want to test. Don't forget to check that they should be included in both your targets. Notice that we mix Cocoa and Cocoa Touch, that's is fine - all code is executed on your Mac. Build again, and this time you'll see in the build log that everything built and the test suite was executed, but contained 0 test cases. Let's remedy that.
</p>
<h2>Writing test cases</h2>
<p>
Next we want to write our first test case. Open up CalculatorTest.m and add the following method:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int result = [calculator add:5 to:6];
}</pre>
<p>All methods that start with "test" will be recognized as being a test case, and automatically run when building the target. Try and build and you'll unsurprisingly get the erro "unrecognized selector sent to instance...". That's all good. Let's add the add method to our Calculator class. In Calculator.h add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b;</pre>
<p>Then in Calculator.m add:</p>
<pre class="brush:objc">-(int)add:(int)a to:(int)b
{
        return 0;
}</pre>
<p>That should be enough to let it compile and run, right? Try it out! You'll see that it indeed build and executes the tests.
</p>
<p>
        Now we change the test so that it actually checks that we get the expected value back. We want to "assert" that the returned value is what we expected. Change the test case to look like this:</p>
<pre class="brush:objc">-(void)testAdd
{
        Calculator* calculator = [[Calculator alloc] init];
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>Build and you see that the test runs and fails since our calculator always returns 0 regardless of the input. Change the production code so that it returns a+b and rerun the test. Nice, we have a successful build and our test works! Notice the fast cycle of test, code, fix, rerun. The point of TDD is to write tests and production code in small iterations so that you always have something stable (= the tests pass). If you follow the rules of TDD you'll have a growing amount of test cases and you'll right away know when something breaks.
</p>
<p>
Let's write one more test. Now we want to add the functionality to allow one number to be divided by another. Start up like before with a new test case like this:</p>
<pre class="brush:objc">-(void)testDivide
{
        Calculator* calculator = [[Calculator alloc] init];
        float expected = 2.5;
        int result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}</pre>
<p>You see, this time we expect to get back a float. Add the corresponding divide method to Calculator.h and Calculator.m. If you need help see the full code listing at the end of this article. You might notice that just returning a/b gives you 2.0. Type cast the return value to (float)a/b and you'll be fine. Go ahead when you got it working.
</p>
<p>
What happens if you try to divide something with zero? Well, why not add a test case for this scenario? If you're into maths you know that the result of this operation is undefined. How do you expect something to be undefined? This is tricky. <img src='http://blog.jayway.com/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  Start off by just expecting any number and see what you get back. As you see, the float value "inf" is returned. It seems like Objective-C treats the zero as "a value approaching zero" and that will indeed result in infinity in a division. But, hey, that might not be what we want our calculator to do. Let's change the test case to expect an exception to be raised instead:</p>
<pre class="brush:objc">-(void)testDivideByZero
{
        Calculator* calculator = [[Calculator alloc] init];
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}</pre>
<p>Build and notice the error message when no exception was raised. Now change the production code to something like this:</p>
<pre class="brush:objc">-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}</pre>
<p>Rerun and smile as the test passes! There are many different variants of asserts you can do with SenTestingKit. Compare objects with STAssertEqualObjects. STAssertTrue to check that a returned boolean is true. Open up SentTestCase_Macros.h if you want to see what you can play around with. By the way. You might have tried using NSLog in your test cases (just to experiment). This is nothing you would do in real life, as you want all necessary information in the fail message and output nothing if the test passes. Anyway, since the tests are actually run using a separate shell script for the UnitTest target you won't see the log in your console as usual. Instead check the build log and click the "text" icon to the right for the "Run test suite" step.
</p>
<h2>Wrapping up</h2>
<p>
Finally, if you look at your test class you might notice that we're allocating a new Calculator for every test case, and we never release them. That's no good. Luckily there are setUp and tearDown methods that will be launched automatically before and after each test case. Change your implementation to look like this (this is the final listing):</p>
<pre class="brush:objc">#import &lt;SenTestingKit/SenTestingKit.h&gt;
#import "Calculator.h"
@interface CalculatorTest : SenTestCase
{
        Calculator* calculator;
}
@end

@implementation CalculatorTest

- (void) setUp
{
        calculator = [[Calculator alloc] init];
}

-(void)tearDown
{
        [calculator release];
}

-(void)testAdd
{
        int expected = 11;
        int result = [calculator add:5 to:6];
        STAssertEquals(expected, result,
                @"We expected %d, but it was %d",expected,result);
}

-(void)testDivide
{
        float expected = 2.5;
        float result = [calculator divide:5 by:2];
        STAssertEquals(expected, result,
                @"We expected %f, but it was %f",expected,result);
}

-(void)testDivideByZero
{
        STAssertThrows([calculator divide:5 by:0],
                @"We expected an exception to be raised when dividing by 0");
}
@end</pre>
</p>
<p>
For completeness, here's the listing for Calculator.h:</p>
<pre class="brush:objc">#import <Foundation/Foundation.h>

@interface Calculator : NSObject {

}

-(int)add:(int)a to:(int)b;
-(float)divide:(int)a by:(int)b;

@end</pre>
<p>and for Calculator.m:</p>
<pre class="brush:objc">#import "Calculator.h"

@implementation Calculator

-(int)add:(int)a to:(int)b
{
        return a+b;
}

-(float)divide:(int)a by:(int)b
{
        float result =  (float)a/b;
        if (result==INFINITY) {
                [NSException raise:@"Cannot divide by zero!"
                            format:@"Not possible to divide %d with %d", a,b];
        }
        return result;
}

@end</pre>
<p>Next blog post we'll see how to automate the running of test cases on a build server called Hudson!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2010/01/15/test-driven-development-in-xcode/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Introduction to  iPhone development</title>
		<link>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/</link>
		<comments>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/#comments</comments>
		<pubDate>Fri, 01 May 2009 08:50:37 +0000</pubDate>
		<dc:creator>Christian Hedin</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[jayview]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.jayway.com/?p=2920</guid>
		<description><![CDATA[It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. Introduction Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together [...]]]></description>
			<content:encoded><![CDATA[<p><strong>It has been little more than 2 years since the iPhone was first announced and during that time it has managed to make a huge impact on the mobileindustry. </strong></p>
<h2>Introduction</h2>
<p>Just recently, iPhone sales figures surpassed all windows mobile phones combined and in several markets the iPhone has been a top selling phone model. Together with the launch of App Store, Apple has managed to create a service delivery platform that attracts not only the hardcore users, but also the average Joe. A testament to this is the fact that App Store has had over one billion application downloads with over 50 000 applications available. This large potential customer base, combined with the advantage of having virtually no device fragmentation, makes it quite an attractive platform for mobile application developers. The business model is also lucrative, with Apple offering 70% of revenues from the store to instantly go to the seller of the app without having to pay for distribution or anything else than a one time fee. In this regard, the iPhone has certainly helped Apple put the Objective-C language in the limelight. </p>
<p>For the developer, the transition from higher level languages such as Java may<br />
not be so simple as Objective-C has quite a unique syntax. The goal of this<br />
article is to remedy that by going through the main concepts of Objective-C<br />
from a Java perspective. Hopefully this will help you to get a quicker start in your<br />
iPhone development. You should however be aware that it is equally important<br />
to understand how to use the iPhone’s application frameworks in order to create<br />
applications, this article only scratches the surface of the language you will use. </p>
<h3>Objective-C from a Java perspective </h3>
<p>If you are used to both working in C/C++ and Java you might soon recognize<br />
Objective-C as a middle-ground language, meaning that it provides lower-level<br />
mechanisms than Java while being a more manageable and higher-level language<br />
than C/C++. The language is a strict superset of C, which means it’s possible<br />
to write and compile normal C code using the Objective-C compiler. We also<br />
use pointers (signified in code with an asterisk, *) to objects and not references,<br />
like in Java. For object orientation Objective-C uses a syntax similar to that of<br />
Smalltalk, which might take a little time to get used to if you haven’t seen it<br />
before. Objective-C is a highly dynamic language, much like Ruby and Python,<br />
where it’s possible to change the behavior at runtime. The compiler is quite<br />
forgiving and before getting used to this you will likely discover more problems<br />
during runtime than when using Java. </p>
<p>While some of the features in Objective-C are unique, many of them are<br />
similar to those of Java only named differently. In order to ease the transition,<br />
we will use Java terminology as much as possible and step by step build up a<br />
small example in Objective-C that covers the basic features. In some cases the<br />
examples will keep code from previous examples and in some only the change<br />
will be presented to save space. Regardless, the new code is always in bold font.<br />
Let’s get started. </p>
<h3>Classes </h3>
<p>Unlike Java which uses a single .java file, Objective-C separates class declaration<br />
and definition into two files: .h and .m. The .h file is called the interface, which<br />
shouldn’t be confused with Java interfaces (more on this later). Most importantly,<br />
the interface file lists the methods and member variables that the class contains.<br />
A minimal compilable .h file would look like this: </p>
<pre>@interface MyClass {
}
@end</pre>
<p>This piece of code simply declares an empty interface named MyClass which<br />
you preferably should put in a file named “MyClass.h”. The space between the<br />
“{}” signs is where we will put our member variable declarations and the space<br />
right before the @end tag is where method declarations go. The .m file looks like<br />
this: </p>
<pre>#import ”MyClass.h”
@implementation MyClass
@end</pre>
<p>It’s between the lines starting with @implementation and @end that we will<br />
put our actual method implementations. Notice that there are no “{}” signs<br />
since member variables are declared in the interface file. This minimal example<br />
obviously doesn’t do much but it will compile and it it gives us something to<br />
start with. </p>
<p>Similarly to Java, Objective-C has a superclass that most classes inherit from:<br />
NSObject. But while we in Java are used to an implicit inheritance from this<br />
class, we must here explicitly declare this in our .h files. To inherit a class, we<br />
simply add a colon after the class name in our .h file followed by the name of<br />
the class we wish to inherit:  </p>
<pre>@interface MyClass : NSObject {
} </pre>
<p>Conceptually, NSObject has similarities to java.lang.Object. But it is also more<br />
powerful in the sense that it provides some features that are only possible with the<br />
reflection API in Java. As an example, NSObject allows you to take advantage of the<br />
runtime and determine which methods are implemented. It also contains methods<br />
that are needed for proper memory management such as retain and release which<br />
we will look closer at later on.</p>
<h3>Naming conventions</h3>
<p>Objective-C does not provide any type of namespace functionality like Java does<br />
with packages. Instead, to avoid name clashes, the best way is to use prefixes.<br />
You will see this used heavily throughout the official APIs. NSString (a Foundation<br />
class) and UITextField (of the UIKit framework) are two examples. This makes<br />
it easy to see which classes are written by Apple. We recommend that you use<br />
an abbreviation of your company as two upper case characters and prefix your<br />
classes with that. If your company name is Acme, you could use AC as a prefix. </p>
<p>When programming in Objective-C it is advisable to follow the guidelines from<br />
Apple about naming classes, methods and other building blocks. Typically we<br />
want naming to be very expressive and also highly consistent. This contrasts<br />
Java where, for example, some collection classes use addElement(...) and<br />
sometimes add(...) to add new objects. Consistency makes it a lot easier to<br />
learn the frameworks because they follow the same conventions. We also want<br />
to be expressive and really explain in naming what the class or method does.<br />
Java enforces conventions through JavaBeans standards, but Apple goes far<br />
beyond that. For example, ACPeopleTableViewController would be a suitable<br />
name for a Controller (MVC pattern) class that controls a TableView (standard<br />
component) which contains People. When it comes to methods getters should<br />
not be prefixed by “get” but rather have similar name as the property they are<br />
fetching. If there is a property called defaultColor then the method to get it<br />
is called -(NSColor*)color; not getColor();. There are many other naming<br />
conventions and you’ll rather quickly get used to the standard ones. </p>
<h3>Access Control</h3>
<p>There are three types of access control you can set on your member variables:<br />
private, protected, and public. They have the same effect as in Java. The syntax<br />
for doing this is a bit different tough. Let’s add two member variables to our<br />
header file and make these private: </p>
<pre>@interface MyClass
{
    @private
    int firstNumber, secondNumber;
}
@end </pre>
<p>We simply use the compiler directive “@private” and everything beneath it will<br />
be private until either a “}” or another directive is found. </p>
<p>So how do I make my instance methods private? The answer is that you don’t<br />
have to worry about that, since the language doesn’t formally support changing<br />
the access type on methods. All methods are public!</p>
<h3>Methods</h3>
<p>The equivalent of calling methods in Java is defined as sending messages in<br />
Objective-C. This is one of the big differences between the languages. On the<br />
surface it may appear as we are doing the same thing only with different syntax: </p>
<pre>Java:         myObject.doSomething(myParameter);
Objective-C:  [myObject doSomething:myParameter]; </pre>
<p>But there is in fact a big underlying difference. The doSomething method in<br />
the Java example must exist at compile time or the compilation will fail. The<br />
same does not apply in the Objective-C case. The notion of sending a message<br />
to an object implies that we will send something regardless of whether there is<br />
a receiver or not and how the message together with parameters are handled is<br />
determined at runtime. </p>
<p>Now let’s declare a method in our header file that will add two numbers: </p>
<pre>@interface MyClass {
  @private
  int firstNumber, secondNumber;
}
-(int)add:(int)a to:(int)b; </pre>
<p>The syntax may seem confusing at first but the elegance is displayed once the<br />
method is used to pass a message: </p>
<pre>[myObject add:5 to: 2];</pre>
<p>Notice the readability of that method. Instead of guessing or reading<br />
documentation for method signatures we know right away which parameter<br />
goes where. Now lets add the implementation in the .m file: </p>
<pre>-(int)add:(int)a to:(int)b
{
    return b + a;
} </pre>
<h3>Constructors </h3>
<p>Objective-C doesn’t have the same concept of constructors as Java. Instead,<br />
object creation is divided into two parts: allocation and initialization. There is<br />
no special syntax reserved for object creation (i.e. new in Java). The methods<br />
handling this are regular methods and are named alloc and init respectively. The<br />
two calls are usually nested to allocate and initialize an object on a single line: </p>
<pre>MyClass *myObject = [[MyClass alloc] init];</pre>
<p>Notice the star in front of myObject. This is regular C syntax for declaring<br />
a pointer. Now pointers are usually something that Java people like to avoid<br />
since it can be the source of all kinds of troubles. Fortunately, if you stick to<br />
using Objective-C you almost never have to use the star or any dereference<br />
mechanism when actually using the objects. Just keep in mind that it has to be<br />
there in the declaration. </p>
<p>The alloc method is a static method that resides in NSObject and should never<br />
be overridden. It allocates memory and returns a new instance of the receiving<br />
class. The init method on the other hand is an instance method and should be<br />
overwritten. In fact, the default implementation does nothing but return itself.<br />
The simplest form of init implementation usually looks like this: </p>
<pre>- (id)init
 {
     if ((self = [super init])) {
         /* class-specific initialization goes here */
 }
     return self;
 } </pre>
<p>We always call the parent’s init method and make sure we get something back.<br />
Then we execute our initialize code and return self which is the Objective-C<br />
equivalent of Java’s <em>this</em>.</p>
<p>Just like you often have multiple constructors in Java, you will likely have<br />
more than one initializer in your Objective-C class that takes different types of<br />
arguments. According to convention you should start the name of these methods<br />
with “initWith”. Here’s an initializer that takes two numbers as parameters: </p>
<pre>- (id) initWithNumberA:(int)numberA numberB:(int)numberB
 {
     if ((self = [super init])) {
        firstNumber = numberA;
        secondNumber = numberB;
     }
     return self;
 } </pre>
<p>The convention also says that only one initializer should make the call to super.<br />
It is often convenient to do this in the initializer with the most arguments, and<br />
let the other initializers call that one. Let’s change the first initializer so it looks<br />
like this: </p>
<pre>- (id)init
 {
     return [self initWithNumberA:0 numberB:0];
 } </pre>
<h3>Protocols</h3>
<p>Protocols are essentially the same thing as Java interfaces but with added flexibility.<br />
A class is not always required to implement all methods just to conform to the<br />
protocol, some can be marked as optional. Furthermore, a class can conform to a<br />
protocol by just implementing the required methods, even if it hasn’t explicitly<br />
declared that it is implementing it. Let’s create our own protocol to indicate that<br />
the example class can calculate something, and suitably call it Calculator. We<br />
enter the following in a new .h named CalculatorProtocol.h. </p>
<pre>@protocol Calculator
@required
-(int)calculate;
@end </pre>
<p>The protocol declaration is pretty straight forward. The @required attribute<br />
signifies that the method is mandatory to implement. We could also have written<br />
@optional if we don’t want to force an implementation. It’s also possible to mix<br />
required and optional methods. Now to show that our example class conforms<br />
to this protocol we first change the .h file: </p>
<pre>#import ”CalculatorProtocol.h”
@interface MyClass : NSObject <Calculator>
{ ... </pre>
<p>And then we add the implementation of our getCalculation method in the .m<br />
file:</p>
<pre>-(int)calculate
{
    return [self add:firstNumber to:secondNumber];
} </pre>
<h3>Where’s my garbage collector?</h3>
<p>Unlike Java and desktop Objective-C development there is no garbage collector<br />
available when creating applications for the iPhone. The reason for this is to<br />
allow the best possible performance. This means that you will have to clean up<br />
after yourself manually. Fortunately, the NSObject class contains functionality<br />
to make manual memory management easier. Every object whose class inherits<br />
from NSObject contains a so called retain count which is used to indicate how<br />
many other objects that are using or “owning” it. If you own an object, you are<br />
also responsible for releasing it when you are done, at which point the retain<br />
count willl go down. When the retain count reaches 0 the system will assume it’s<br />
safe to deallocate the memory for your object. So when is the object considered<br />
“used”, i.e. when does the retain count go up? First of all, the retain count will<br />
implicitly increase if you you create the object yourself by using a method name<br />
beginning with “alloc”, “new” or contains “copy”. Secondly, you must explicitly<br />
add one to the retain counter by calling the NSObject method “retain” whenever<br />
you wish to take ownership of an object that you receive by other means, i.e. as<br />
a parameter or from a getter method. </p>
<p>To reduce the retain count, or say that you no longer need the object in question,<br />
you use [myObject autorelease] or [myObject release], where autorelease<br />
signifies that the object should release later. To show how this works we add the<br />
following to our example: </p>
<pre>-(void) setName: (NSString*) newName
{
    [newName retain]; // get ownership, increases retain count for newName
    [name release]; // in case name is already set, we don’t need it anymore
    name = newName; // set name to the new value
} </pre>
<p>We need to retain newName in case we are passing the same object that is<br />
currently assigned to name, or it might be deallocated. When releasing name it’s<br />
possible that it’s not set, but it’s fine to call release on a nil object.</p>
<p>There are situations when you want to autorelease objects. For instance, if you<br />
have a method that returns a NSString that is created inside the method: </p>
<pre>//PROBLEMATIC CODE
-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted release];
  return formatted;
} </pre>
<p>If you run this code there’ll be problems. The formatted variable will be released<br />
before it’s returned which means that whoever requested the NSString will get<br />
a pointer to a freed object. The solution is to replace release with autorelease.<br />
Objects that are sent autorelease will be added to an autorelease pool. When<br />
the pool is deallocated release is sent to all objects it contains, including our NSString. The pool is created before events and deallocated when the event has<br />
been handled. That way the formatted variable won’t be deallocated right away. </p>
<pre>-(NSString*)formattedName
{
  NSString *formatted = [[NSString alloc] initWithFormat:@”Name: %@”,name];
  [formatted autorelease];
  return formatted;
}
</pre>
<p>All objects that are not created using alloc, new or copy are automatically added<br />
to the current autorelease pool. So if you don’t want to loose those objects you<br />
need to retain them.</p>
<p>Many objects have convenience methods that return autoreleased objects, so<br />
the easiest solution to our problem would be to avoid the alloc and instead use<br />
a convenience method:</p>
<pre>-(NSString*)formattedName
{
  return [NSString stringWithFormat:@”Name: %@”, name];
} </pre>
<p>Manual memory management is usually one of the tougher parts to get used to<br />
when coming from a “friendlier” language such as Java. It is important however<br />
to get a good understanding in this area as it often can be the source of nasty<br />
bugs. </p>
<h3>Conclusions</h3>
<p>That concludes our example and short introduction to Objective-C, the<br />
language you need to master - or at least learn to use - in order to write great<br />
iPhone applications. The syntax and some concepts differ a bit from Java, but<br />
it’s relatively easy to pick up and get started with. There are many other areas<br />
we haven’t even touched upon, such as the frameworks and tools provided by<br />
Apple. Fortunately there’s a wealth of information available online at the iPhone<br />
Dev Center, where you can read API references, download sample code, watch<br />
tutorial guides and videos as well as discuss with other developers. In order to<br />
develop applications for iPhone you need a Mac computer running Mac OS X<br />
and register as a developer (for free) on Apple’s website. Good luck! </p>
<p><em>Christian Hedin<br />
Stefan Li </em></p>
<p><em>Originally published in <a href="http://jayway.se/jayview">JayView</a>.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jayway.com/2009/05/01/introduction-to-iphone-development/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
