<?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>bytesizecreations &#187; instruments</title>
	<atom:link href="http://www.bytesizecreations.com/category/instruments/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bytesizecreations.com</link>
	<description>Musings from a busy mind</description>
	<lastBuildDate>Sun, 14 Jun 2009 17:44:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Objective-C: Tips for a Java Programmer</title>
		<link>http://www.bytesizecreations.com/2008/10/objective-c-tips-for-java-programmer/</link>
		<comments>http://www.bytesizecreations.com/2008/10/objective-c-tips-for-java-programmer/#comments</comments>
		<pubDate>Sun, 12 Oct 2008 06:27:00 +0000</pubDate>
		<dc:creator>Michael Gaylord</dc:creator>
				<category><![CDATA[instruments]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[iphone sdk]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[java objective-c comparison]]></category>
		<category><![CDATA[key-value coding]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://www.42restaurants.com/byte/?p=43</guid>
		<description><![CDATA[I have been learning Objective-C part-time. Partly to learn something new and different but also partly out of curiosity. As a Java programmer, I initially thought it would be a doddle but as soon as I looked at the code I realised it was going to take a bit of getting used to. After going [...]]]></description>
			<content:encoded><![CDATA[<p>I have been learning Objective-C part-time. Partly to learn something new and different but also partly out of curiosity. As a Java programmer, I initially thought it would be a doddle but as soon as I looked at the code I realised it was going to take a bit of getting used to. After going through Apple’s excellent, yet verbose, guide: <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Introduction/chapter_1_section_1.html">The Objective-C 2.0 Programming Language</a> &#8211; I started to get used to the syntax. Its not that hard, especially if you come from a C or Java background. Here are some of the differences and some of the highlights I have encountered so far.</p>
<p><strong>1. Methods, Functions, Messaging<br /></strong><br />
The most difficult thing to get used to initially is the syntax for calling methods, or as its called in Objective-C: <em>messaging</em>. In Java calling a method on an object looks like this:</p>
<div style="text-align: center;">
  </p>
<div style="text-align: left;">
<div style="text-align: center;">
      <span style="font-family:courier new;">Car car = new Car();</span><br />
      <span style="font-family:courier new;">car.drive(10, 100);</span>
    </div>
</p></div>
<p></p>
<div style="text-align: left;">
    <span style="font-family:courier new;"><span style="font-family:georgia;">This piece of code creates an instance of type</span> car</span> <span style="font-family:georgia;">and then tells it drive 10 kilometres at 100 kilometres and hour. If we were to write the same thing in Objective-C it would look something like this:</p>
<p></span></p>
<div style="text-align: center;">
<div style="text-align: left;">
<div style="text-align: center;">
          <span style="font-family:georgia;"><span style="font-family:courier new;">Car <em>car = [[Car <span class="blsp-spelling-error" id="SPELLING_ERROR_0">alloc</span>] <span class="blsp-spelling-error" id="SPELLING_ERROR_1">init</span>];</em></span><br />
          <span style="font-family:georgia;"><span style="font-family:courier new;">[car drive:10 speed:100];</span></span><br /></span>
        </div>
<p>
        <span class="blsp-spelling-error" id="SPELLING_ERROR_2">Whoaaa</span>! Hold on a minute. That is completely different from Java and C. Well, don’t panic. If you have ever programmed with C or C++ you will probably understand the first bit &#8211; <span style="font-family:courier new;">Car *car. <span style="font-family:georgia;">We are creating a pointer to a place in memory that holds a car. The part after the equals is a little more confusing. The designers of Objective-C have dropped the dot-notation completely for messaging objects. The piece of code <span style="font-family:courier new;">[Car <span class="blsp-spelling-error" id="SPELLING_ERROR_3">alloc</span>]</span> can be rewritten in Java as <span style="font-family:courier new;">Car.<span class="blsp-spelling-error" id="SPELLING_ERROR_4">alloc</span>()</span>.</span></span> In Objective-C, this is the way to allocate a piece of memory for your instance. It is also the way you call methods on instances.</p>
<p>        The closest equivalent to a constructor that I can find in Objective-C is the <span style="font-family:courier new;"><span class="blsp-spelling-error" id="SPELLING_ERROR_5">init</span></span> message call. All objects have an <em><span class="blsp-spelling-error" id="SPELLING_ERROR_6">init</span> method</em> &#8211; inherited from the base object <em><span class="blsp-spelling-error" id="SPELLING_ERROR_7">NSObject</span></em> (in Java this would be equivalent to <em>Object</em>). You can override the <span style="font-family:courier new;"><span class="blsp-spelling-error" id="SPELLING_ERROR_8">init</span></span> method in your classes to add initialisation code.</p>
<p>        So the first line in our example now makes sense, but what about the second line? Objective-C uses the concept of <em>named arguments</em>. This may seem redundant or a little verbose, but once you get used to it, it does make it <a href="http://parveenkaler.com/2008/09/28/iphone-development-reading-objective-c-methods/">easier to read</a>. This syntax scheme is an adaptation of the way you would message objects in <a style="font-style: italic;" href="http://en.wikipedia.org/wiki/Smalltalk">Smalltalk</a>. So we are basically messaging our instance of car to drive 10 at the speed of 100. I could have possibly made the method a little more informative and written it as: <span style="font-family:courier new;">[car <span class="blsp-spelling-error" id="SPELLING_ERROR_9">driveFor</span>:10 speed:100]</span>.</p>
<p>        <strong>2. Garbage Collection vs. Retain Counts</p>
<p></strong>Since Mac OS X 10.5, Mac developers have been treated to the simplicity of writing code without having to worry about memory management &#8211; in other words, <a href="http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29"><em>Garbage Collection</em></a> has been introduced. The only thing to bear in mind is that if you want to write code that is supported by older versions of Mac OS X, namely, 10.4 and the iPhone you will still need manage your memory manually. Fortunately, detecting memory leaks is fairly simple with the Apple developer tool <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/chapter_1_section_1.html">Instruments</a>.</p>
<p>        The mechanism by which you manage memory manually is called <a href="http://en.wikipedia.org/wiki/Cocoa_%28API%29#Memory_management"><em>retain counts</em></a>. Every time you make an object point to another object you increase that object’s retain count. This loosely means that if you have 10 pointers pointing to an instance, the instance will have a retain count of 10. Whenever you are finished with a pointer you need to <em>release</em> the object. This drops the instance’s retain count by 1. When an instance’s retain count reaches 0 it will be <span class="blsp-spelling-error" id="SPELLING_ERROR_10">deallocated</span>.</p>
<p>        There are many pitfalls with manual memory management. Having a <a href="http://en.wikipedia.org/wiki/Memory_leak">memory leak</a> means that over time your application will consume more and more memory and it will crash the system eventually. There are 2 main ways you can create a memory leak. The first is to have an orphaned object. This is where the object has a retain count greater than zero but there are no other objects pointing to it. The other is to have a retain cycle. This is where <em>Object A</em> points to <em>Object B</em> and <em>Object B</em> points to <em>Object A</em>, and nothing else points to these two objects.</p>
<p>        If you want to build applications for the iPhone or for older versions of Mac <span class="blsp-spelling-error" id="SPELLING_ERROR_11">OS X</span> then you need to be more meticulous with your code. Make sure that your objects always clean up after themselves and use the application <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/chapter_1_section_1.html">Instruments</a> to ensure you have no memory leaks. On the iPhone memory leaks can be disastrous, since you only have a very limited amount of memory to play with. Should your application run out of the allocated memory on the iPhone, it will <em>reboot</em> &#8211; basically quit your application.</p>
<p>        <strong>3. Cool Extras<br /></strong><br />
        Objective-C has some really cool features built into it and some downright weird ones. Two really cool features that have no equivalents in Java are: <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/KeyValueCoding/"><em>Key-Value Coding</em></a> and <em>@synthesize/@property</em> directives.</p>
<p>        <em>Key-Value Coding</em> is a very neat and dynamic way of querying objects by name. Some people would say that you can do similar tricks in Java with <a href="http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html"><em>Reflection</em></a> but Key-Value Coding has a lot more useful features that you cannot leverage in Java without writing a lot of code.</p>
<p>        Key-Value Coding works like this:</p>
<div style="text-align: center;font-family:courier new;">
          Car *car = [[Car <span class="blsp-spelling-error" id="SPELLING_ERROR_12">alloc</span>] <span class="blsp-spelling-error" id="SPELLING_ERROR_13">init</span>];<br />
          [car <span class="blsp-spelling-error" id="SPELLING_ERROR_14">setValue</span>:@”BMW” <span class="blsp-spelling-error" id="SPELLING_ERROR_15">forKey</span>:@”<span class="blsp-spelling-error" id="SPELLING_ERROR_16">carMaker</span>”];</p>
<div style="text-align: left;">
            <span style="font-family:georgia;">Basically, we are setting the value for the property <span class="blsp-spelling-error" id="SPELLING_ERROR_17" style="font-family:courier new;">carMaker</span> to <em>BMW</em>. This seems cumbersome, but bear with me. We can now retrieve the value in the following manner:</p>
<p></span></p>
<div style="text-align: center;">
              <span style="font-family:courier new;"><span class="blsp-spelling-error" id="SPELLING_ERROR_18">NSString</span> *<span class="blsp-spelling-error" id="SPELLING_ERROR_19">carMakerString</span> = [car <span class="blsp-spelling-error" id="SPELLING_ERROR_20">valueForKey</span>:@”<span class="blsp-spelling-error" id="SPELLING_ERROR_21">carMaker</span>”];</span></p>
<div style="text-align: left;">
                <span style="font-family:georgia;">We can now read and set objects by their values. The cool thing is that you don’t need to cast any values. The <span class="blsp-spelling-error" id="SPELLING_ERROR_22" style="font-family:courier new;">valueForKey</span> method will automatically cast the value for you. Programmer’s used to dynamic languages will probably laugh at the significance of this but if you are from a Java background you will appreciate not having to check and cast the result of the call.</p>
<p>                You can also describe <em><span class="blsp-spelling-error" id="SPELLING_ERROR_23">keypaths</span></em> for key-values. A <span class="blsp-spelling-error" id="SPELLING_ERROR_24">keypath</span> is basically a way of navigating a pointer graph to a property from object to object. For example:</span>
              </div>
</p></div>
</p></div>
</p></div>
<p></p>
<div style="text-align: center;">
          <span style="font-family:courier new;"><span class="blsp-spelling-error" id="SPELLING_ERROR_25">NSNumber</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_26">topSpeed</span></span> = [car <span class="blsp-spelling-error" id="SPELLING_ERROR_27">valueForKeyPath</span>:@”<span class="blsp-spelling-error" id="SPELLING_ERROR_28">carMaker</span>.<span class="blsp-spelling-error" id="SPELLING_ERROR_29">topSpeed</span>”];</p>
<div style="text-align: left;">
            <span style="font-family:georgia;">Where <span style="font-family:courier new;"><span class="blsp-spelling-error" id="SPELLING_ERROR_30">topSpeed</span></span> is a method that returns an int for the car’s top speed.</span> The <span style="font-family:courier new;">int</span> will be <em>auto-boxed</em> to an <em><span class="blsp-spelling-error" id="SPELLING_ERROR_31">NSNumber</span></em> at <span class="blsp-spelling-error" id="SPELLING_ERROR_32">runtime</span>.</p>
<p>            In addition to <span class="blsp-spelling-error" id="SPELLING_ERROR_33">keypaths</span>, there are also <em><span class="blsp-spelling-error" id="SPELLING_ERROR_34">aggregator</span> functions</em> you can use on key-values in arrays. So for instance, if we have an array of car objects and we want the average top speed of all the cars at the BMW dealer we could do the following:</p>
<div style="text-align: center;">
              <span style="font-family:courier new;">double <span class="blsp-spelling-error" id="SPELLING_ERROR_35">averageSpeed</span> = [<span class="blsp-spelling-error" id="SPELLING_ERROR_36">bmwDealer</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_37">valueForKey</span>:@”cars.@avg.topSpeed”];</p>
<p></span></p>
<div style="text-align: left;">
                <span style="font-family:courier new;"><span style="font-family:georgia;">If we wanted to something similar in Java or without key-values we would have to loop through the whole array of cars, add the top speeds to a variable and then divide by the number of cars in the array.</span></span> If you want to learn more about Key-Value Coding, including the most powerful feature for binding values, called <em>Key-Value Observing</em>, check <a href="http://www.informit.com/articles/article.aspx?p=425173">this article out</a>.</p>
<p>                Another cool feature that Objective-C contains, that I use all the time are the <span style="font-family:courier new;">@property/@synthesize</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_38">preprocessor</span> directives. The combination of these eliminates the need to write boilerplate getter and setter code. The <span style="font-family:courier new;">@property</span> directive, used in the header file for a class, tells the compiler that this is a property of the class. In addition you can make the property read only or readable/writable, by adding <span style="font-family:courier new;">read</span> or <span class="blsp-spelling-error" id="SPELLING_ERROR_39" style="font-family:courier new;">readwrite</span> in brackets like this:</p>
<div style="text-align: center;">
                  <span style="font-family:courier new;">@property(read) int <span class="blsp-spelling-error" id="SPELLING_ERROR_40">topSpeed</span>;<br /></span></p>
<div style="text-align: left;">
                    <span style="font-family:courier new;"><span style="font-family:georgia;">Or</span></span>,</p>
<div style="text-align: center;">
                      <span style="font-family:courier new;">@property(<span class="blsp-spelling-error" id="SPELLING_ERROR_41">readwrite</span>) <span class="blsp-spelling-error" id="SPELLING_ERROR_42">NSString</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_43">carMaker</span>;</span></p>
<div style="text-align: left;">
                        You can also tell the compiler how to manage the memory for the getter and setter of that property by putting a retain, assign or copy after. Like this:</p>
<div style="text-align: center;">
                          <span style="font-family:courier new;">@property(read, retain) <span class="blsp-spelling-error" id="SPELLING_ERROR_44">NSString</span> <span class="blsp-spelling-error" id="SPELLING_ERROR_45">carMaker</span></span>;</p>
<div style="text-align: left;">
                            By adding <span style="font-family:courier new;">@synthesize</span> in your class file for your properties. The compiler will automatically generate getter and setter methods for you.</p>
<div style="text-align: center;">
                              <span style="font-family:courier new;">@synthesize <span class="blsp-spelling-error" id="SPELLING_ERROR_46">carMaker</span>;</span>
                            </div>
</p></div>
</p></div>
<p>
                        <strong>4. So Far, So Good</strong></p>
<p>                        So far my experiences with Objective-C have been favourable. I do get confused sometimes when my code won’t compile and it looks correct, only to realise that it would be correct in Java but will never work in Objective-C. Apple’s <a href="http://developer.apple.com/tools/interfacebuilder.html"><span class="blsp-spelling-error" id="SPELLING_ERROR_47">Interface</span> Builder</a> software is top notch and makes designing and hooking up your interface very simple. <a href="http://developer.apple.com/tools/xcode/"><span class="blsp-spelling-error" id="SPELLING_ERROR_48">XCode</span></a>’s code editore on the other hand, in my opinion, is a bit behind compared to <a href="http://www.eclipse.org/">Eclipse</a>. A Mac developer would, however, probably class Eclipse as bloatware. <a href="http://developer.apple.com/documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/chapter_1_section_1.html">Instruments</a> is my favourite and makes optimising your application and finding memory leaks a doddle.
                      </div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</p></div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.bytesizecreations.com/2008/10/objective-c-tips-for-java-programmer/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
