<?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>DaveOnCode &#187; iphone</title>
	<atom:link href="http://www.daveoncode.com/tag/iphone/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.daveoncode.com</link>
	<description>Objective C, iOS and more programming stuff</description>
	<lastBuildDate>Mon, 19 Dec 2011 12:11:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Quick iOS tip: invoke UITableView dataSource and delegate methods from a UITableViewCell</title>
		<link>http://www.daveoncode.com/2011/11/28/quick-ios-tip-invoke-uitableview-datasource-delegate-methods-from-uitableviewcell/</link>
		<comments>http://www.daveoncode.com/2011/11/28/quick-ios-tip-invoke-uitableview-datasource-delegate-methods-from-uitableviewcell/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 13:03:43 +0000</pubDate>
		<dc:creator>Davide Zanotti</dc:creator>
				<category><![CDATA[Objective-c and Cocoa]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[UITableView]]></category>

		<guid isPermaLink="false">http://www.daveoncode.com/?p=866</guid>
		<description><![CDATA[I faced a situation in my app where I wanted to access to UITableView datasource from a UITableViewCell. Specifically I implemented the same behavior of left green (+) button in the label contained in the cell, so if you click on it the editing action &#8220;UITableViewCellEditingStyleInsert&#8221; will be committed. Since a cell is contained in [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/11/28/quick-ios-tip-invoke-uitableview-datasource-delegate-methods-from-uitableviewcell/' addthis:title='Quick iOS tip: invoke UITableView dataSource and delegate methods from a UITableViewCell ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>I faced a situation in my app where I wanted to access to <strong>UITableView</strong> datasource from a <strong>UITableViewCell</strong>. Specifically I implemented the same behavior of left green (+) button in the label contained in the cell, so if you click on it the editing action &#8220;<strong>UITableViewCellEditingStyleInsert</strong>&#8221; will be committed.<br />
Since a cell is contained in a table we can easily access to it using <strong>self.superview</strong> (cast is required because superview returns a basic <strong>UIView</strong> *), then once we are sure that the table has a valid dataSource, we can manually invoke the selector <strong>tableView:commitEditingStyle:forRowAtIndexPath:</strong>. In order to pass the proper <strong>indexPath</strong> dynamically we rely on table method <strong>indexPathForCell:</strong> (we don&#8217;t know in which cell we are but table does!).<br />
The complete code snippet is the following:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">UITableView <span style="color: #339933;">*</span>table <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>UITableView <span style="color: #339933;">*</span><span style="color: #009900;">&#41;</span>self.<span style="color: #202020;">superview</span><span style="color: #339933;">;</span><br />
SEL sel <span style="color: #339933;">=</span> @selector<span style="color: #009900;">&#40;</span>tableView<span style="color: #339933;">:</span>commitEditingStyle<span style="color: #339933;">:</span>forRowAtIndexPath<span style="color: #339933;">:</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#91;</span>table isKindOfClass<span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span>UITableView class<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#91;</span>table.<span style="color: #202020;">dataSource</span> respondsToSelector<span style="color: #339933;">:</span>sel<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#91;</span>table.<span style="color: #202020;">dataSource</span> tableView<span style="color: #339933;">:</span>table <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;commitEditingStyle<span style="color: #339933;">:</span>UITableViewCellEditingStyleInsert <br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; forRowAtIndexPath<span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span>table indexPathForCell<span style="color: #339933;">:</span>self<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/11/28/quick-ios-tip-invoke-uitableview-datasource-delegate-methods-from-uitableviewcell/' addthis:title='Quick iOS tip: invoke UITableView dataSource and delegate methods from a UITableViewCell ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncode.com/2011/11/28/quick-ios-tip-invoke-uitableview-datasource-delegate-methods-from-uitableviewcell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting right UIImage and CGImage pixel size according to device display (retina or not)</title>
		<link>http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/</link>
		<comments>http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/#comments</comments>
		<pubDate>Sat, 22 Oct 2011 16:31:50 +0000</pubDate>
		<dc:creator>Davide Zanotti</dc:creator>
				<category><![CDATA[Objective-c and Cocoa]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://www.daveoncode.com/?p=836</guid>
		<description><![CDATA[I just fixed an issue related to the wrong display of an UIImageView in my (never ending WIP) app. The problem is that starting with iOS 4 and with the introduction of retina display in iPhone 4, the attribute &#8220;size&#8221; does not return the real pixel dimensions but points. So on a retina display device [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/' addthis:title='Getting right UIImage and CGImage pixel size according to device display (retina or not) ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>I just fixed an issue related to the wrong display of an <strong>UIImageView</strong> in my (never ending WIP) app. The problem is that starting with <strong>iOS 4</strong> and with the introduction of retina display in iPhone 4, the attribute <strong>&#8220;size&#8221;</strong> does not return the real pixel dimensions but points. So on a retina display device an image of <strong>100&#215;100</strong> pixel will return a size of <strong>200&#215;200</strong> (values are doubled). Theoretically there is an helpful attribute <strong>&#8220;scale&#8221;</strong> that should return a float value representing the adopted scale (2.0f for retina display, 1.0f for other).<br />
Unfortunately, in my case it returns always 1, both for the iOS simulator than the real device (iPhone 4 with iOS 5), and my images are rendered incorrectly.<br />
After digging on Google (which as usual points me to my beloved Stackoverflow), I gathered several helpful informations that helped me solving the problem and inspired a few helpful precompiler macros :)<br />
The <strong>scale</strong> value, which is essential to implement retina display-aware software can be retrieved using:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>UIScreen mainScreen<span style="color: #009900;">&#93;</span> scale<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>So, I realized the following macros:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// return true if the device has a retina display, false otherwise</span><br />
<span style="color: #339933;">#define IS_RETINA_DISPLAY() [[UIScreen mainScreen] respondsToSelector:@selector(scale)] &amp;&amp; [[UIScreen mainScreen] scale] == 2.0f</span><br />
<br />
<span style="color: #666666; font-style: italic;">// return the scale value based on device's display (2 retina, 1 other)</span><br />
<span style="color: #339933;">#define DISPLAY_SCALE IS_RETINA_DISPLAY() ? 2.0f : 1.0f</span><br />
<br />
<span style="color: #666666; font-style: italic;">// if the device has a retina display return the real scaled pixel size, otherwise the same size will be returned</span><br />
<span style="color: #339933;">#define PIXEL_SIZE(size) IS_RETINA_DISPLAY() ? CGSizeMake(size.width/2.0f, size.height/2.0f) : size</span></div></td></tr></tbody></table></div>
<p>Then I used a little trick, to initialize an UIImage with the correct dimensions. Fundamentally I initialize an &#8220;helper image&#8221; first from which extract a CGImage in order to allocate a new UIImage using the initializer <strong>initWithCGImage:scale:orientation:</strong> (as scale I use the previous defined macro DISPLAY_SCALE).</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">UIImage <span style="color: #339933;">*</span>helperImage <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>UIImage alloc<span style="color: #009900;">&#93;</span> initWithData<span style="color: #339933;">:</span>data<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
UIImage <span style="color: #339933;">*</span>pic <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>UIImage alloc<span style="color: #009900;">&#93;</span> initWithCGImage<span style="color: #339933;">:</span>helperImage.<span style="color: #202020;">CGImage</span> scale<span style="color: #339933;">:</span>DISPLAY_SCALE orientation<span style="color: #339933;">:</span>UIImageOrientationUp<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/' addthis:title='Getting right UIImage and CGImage pixel size according to device display (retina or not) ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncode.com/2011/10/22/right-uiimage-and-cgimage-pixel-size-retina-display/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ALAssetsLibrary&#8217;s enumerateGroupsWithTypes:usingBlock:failureBlock: on iOS 4.3.4</title>
		<link>http://www.daveoncode.com/2011/07/24/alassetslibrary-not-working-iphone-ipad-ios-4-3-4/</link>
		<comments>http://www.daveoncode.com/2011/07/24/alassetslibrary-not-working-iphone-ipad-ios-4-3-4/#comments</comments>
		<pubDate>Sun, 24 Jul 2011 12:38:20 +0000</pubDate>
		<dc:creator>Davide Zanotti</dc:creator>
				<category><![CDATA[Objective-c and Cocoa]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://www.daveoncode.com/?p=794</guid>
		<description><![CDATA[I had 20 minutes of panic after installing iOS 4.3.4 on my iPhone 4. In fact, the app which I’m developing has stopped working due to a change in the ALAssetsLibrary api. The call to enumerateGroupsWithTypes:usingBlock:failureBlock:, which I use to retrieve all the media files on the device, did nothing (blocks didn’t get called and [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/07/24/alassetslibrary-not-working-iphone-ipad-ios-4-3-4/' addthis:title='ALAssetsLibrary&#8217;s enumerateGroupsWithTypes:usingBlock:failureBlock: on iOS 4.3.4 ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>I had 20 minutes of panic after installing iOS <strong>4.3.4</strong> on my iPhone 4. In fact, the app which I’m developing has stopped working due to a change in the ALAssetsLibrary api. The call to <strong>enumerateGroupsWithTypes:usingBlock:failureBlock:</strong>, which I use to retrieve all the media files on the device, did nothing (blocks didn’t get called and no error raised). After a couple of tests:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;is selector available? %@&quot;</span><span style="color: #339933;">,</span> <br />
<span style="color: #009900;">&#91;</span>library respondsToSelector<span style="color: #339933;">:</span>@selector<span style="color: #009900;">&#40;</span>enumerateGroupsWithTypes<span style="color: #339933;">:</span>usingBlock<span style="color: #339933;">:</span>failureBlock<span style="color: #339933;">:</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">?</span> @<span style="color: #ff0000;">&quot;y&quot;</span> <span style="color: #339933;">:</span> @<span style="color: #ff0000;">&quot;n&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;I'm on the main thread? %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>NSThread isMainThread<span style="color: #009900;">&#93;</span> <span style="color: #339933;">?</span> @<span style="color: #ff0000;">&quot;y&quot;</span> <span style="color: #339933;">:</span> @<span style="color: #ff0000;">&quot;n&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>I figured out that the fetching didn’t begins because it was invoked on a background thread (although this did works fine in iOS <strong>4.3.3</strong>!).<br />
In fact I’m using an NSOperationQueue with several NSOperations inside and one of them is the one invoking ALAssetsLibrary’s api.<br />
So, to solve the problem I simply created a wrapper to the call using <strong>performSelectorOnMainThread:withObject:waitUntilDone:</strong></p>
<p><strong>UPDATE:</strong><br />
After a code refactoring and the upgrade to iOS 5, I finally realized that the problem is actually related to how <strong>ALAssetsLibrary</strong> works. <a href="http://www.daveoncode.com/2011/10/15/solve-xcode-error-invalid-attempt-to-access-alassetprivate-past-the-lifetime-of-its-owning-alassetslibrary/">read here! </a></p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2011/07/24/alassetslibrary-not-working-iphone-ipad-ios-4-3-4/' addthis:title='ALAssetsLibrary&#8217;s enumerateGroupsWithTypes:usingBlock:failureBlock: on iOS 4.3.4 ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncode.com/2011/07/24/alassetslibrary-not-working-iphone-ipad-ios-4-3-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Working with Cocoa dates objects</title>
		<link>http://www.daveoncode.com/2010/11/15/cocoa-objective-c-iphone-dates-objects/</link>
		<comments>http://www.daveoncode.com/2010/11/15/cocoa-objective-c-iphone-dates-objects/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 18:34:36 +0000</pubDate>
		<dc:creator>Davide Zanotti</dc:creator>
				<category><![CDATA[Objective-c and Cocoa]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[formatters]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[nscalendar]]></category>
		<category><![CDATA[nsdate]]></category>
		<category><![CDATA[nsdateformatter]]></category>
		<category><![CDATA[nstimezone]]></category>
		<category><![CDATA[object oriented]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://www.daveoncode.com/?p=680</guid>
		<description><![CDATA[Preface Using and mastering dates objects in Cocoa is not so straightforward as it would in other languages (such Java, Actionscript, JavaScript&#8230;), where you just rely on a single Date class (ok, latest releases of Java have deprecated this approach, but it was a common practice before as far I know) whose interface provides all [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2010/11/15/cocoa-objective-c-iphone-dates-objects/' addthis:title='Working with Cocoa dates objects ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<h2>Preface</h2>
<p>
Using and mastering dates objects in Cocoa is not so straightforward as it would in other languages (such Java, Actionscript, JavaScript&#8230;), where you just rely on a single <strong>Date</strong> class (ok, latest releases of Java have deprecated this approach, but it was a common practice before as far I know)  whose interface provides all the necessary methods to set, get and modify dates and related informations (like years, months, days and so on). Cocoa instead, takes a more sophisticated approach, increasing the flexibility and the power of the framework. Anyway this freedom comes at an obvious price, it requires a little more code to write and additional concepts and classes to learn. Dates are handled using the 5 classes: <strong>NSDate</strong>, <strong>NSCalendar</strong>, <strong>NSTimeZone</strong>, <strong>NSDateComponents</strong>, <strong>NSDateFormatter</strong>.
</p>
<h2>NSDate</h2>
<p>
<strong>NSDate</strong> is the core class that represents a point in time but it&#8217;s pretty useless alone, in fact we can create instances of this object but without the ability to configure its details (year, month, day, hours, minutes, seconds&#8230;). Its main constructors ([[NSDate alloc] init] and [NSDate date]) return the current date and the only way to initialize a different one (a future or a paste date) with only <strong>NSDate</strong> is by using previously defined dates passing them to <strong>initWithTimeInterval:sinceDate:</strong> or <strong>dateWithTimeIntervalSinceReferenceDate:</strong> otherwise choose among one of the string based constructors that accept string representation of dates (like <strong>initWithString:</strong> or <strong>dateWithString:</strong>). <strong>NSDate</strong> doesn&#8217;t provide much more than constructors, the only concrete methods whose interact with date objects are: <strong>isEqualToDate:</strong>, <strong>earlierDate:</strong>, <strong>laterDate:</strong> and <strong>compare:</strong>. These are used to compare two dates and know which is the earlier and if their are or not the same date. Date computation such finding out years elapsed between two dates, increase a date by an arbitrary amount of days or subtract hours from a date are not possible without using other date-related classes.
</p>
<h2>NSCalendar</h2>
<p>
<strong>NSCalendar</strong> represents a system of reckoning time over extended periods and it&#8217;s related to a concrete calendar, usually the <strong>Gregorian Calendar</strong> which is an international standard for civil use. Anyway is possible to initialize an <strong>NSCalendar</strong> choosing among hebrew, islamic, chinese an others system supported calendars. A nice (not programming related) reading about calendars and their history can be found here: <a href="http://astro.nmsu.edu/~lhuber/leaphist.html">http://astro.nmsu.edu/~lhuber/leaphist.html</a>.<br />
<strong>NSCalendar</strong> exposes methods for date computations and to extract date parts (years, months, days&#8230;) from a date.<br />
In a calendar, day, week, weekday, month, and year numbers are generally 1-based.
</p>
<h2>NSTimeZone</h2>
<p>
A time zone represents a geopolitical region on Earth that has its own standard time. By convention each time zone computes its local time as an offset from the Greenwich Mean Time (GMT) (<a href="http://en.wikipedia.org/wiki/Greenwich_Mean_Time">http://en.wikipedia.org/wiki/Greenwich_Mean_Time</a>).<br />
<strong>NSTimeZone</strong> is a class that handles time zones. A specific time zone can be assigned to an <strong>NSCalendar</strong> to influence its behavior.
</p>
<h2>NSDateComponents</h2>
<p>
This is a simple abstract class (no more than a structure) that incapsulate date&#8217;s parts (year, month, day, hour&#8230;). It&#8217;s used in conjunction with <strong>NSCalendar</strong> to initialize a specific user defined <strong>NSDate</strong>.
</p>
<h2>NSDateFormatter</h2>
<p>
This is as special formatter class that handle conversions from date to a string and vice versa by using the conventional unicode date patterns (<a href="http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns">http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns</a>). <strong>NSDateFormatter</strong> formats dates according to the defined locale, calendar and time zone, if you don&#8217;t specify any of these references it will uses the current system settings.
</p>
<h2>Common dates tasks</h2>
<h3>Print a formatted date:</h3>
<p>
To print a formatted date we have to use <strong>NSDateFormatter</strong> and specify a formatting mask manually (by using <strong>setDateFormat</strong>) or rely on the &#8220;automatic&#8221; masks by choosing among <strong>NSDateFormatterStyle</strong> styles.
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// initialize a date object</span><br />
NSDate <span style="color: #339933;">*</span>currentDate <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSDate alloc<span style="color: #009900;">&#93;</span> init<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #666666; font-style: italic;">// initialize a formatter object</span><br />
NSDateFormatter <span style="color: #339933;">*</span>formatter <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSDateFormatter alloc<span style="color: #009900;">&#93;</span> init<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #666666; font-style: italic;">// set formatter's format</span><br />
<span style="color: #009900;">&#91;</span>formatter setDateFormat<span style="color: #339933;">:</span>@<span style="color: #ff0000;">&quot;eeee, dd MMMM yyyy - HH:mm&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
<span style="color: #666666; font-style: italic;">// print formatted date</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;formatted date: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>formatter stringFromDate<span style="color: #339933;">:</span>currentDate<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>
The code above will print &#8220;<strong>sabato, 13 novembre 2010 &#8211; 12:10</strong>&#8221; on my mac due to my system settings, whose I can check as following:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// get my current time zone</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my time zone: %@ - abbreviation: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSTimeZone systemTimeZone<span style="color: #009900;">&#93;</span> name<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSTimeZone systemTimeZone<span style="color: #009900;">&#93;</span> abbreviation<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #666666; font-style: italic;">// get my current calendar</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my calendar: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSCalendar currentCalendar<span style="color: #009900;">&#93;</span> calendarIdentifier<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #666666; font-style: italic;">// get my current locale</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my locale: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSLocale currentLocale<span style="color: #009900;">&#93;</span> localeIdentifier<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>The NSLogs will print:</p>
<ul>
<li>&#8220;my time zone: Europe/Rome &#8211; abbreviation: GMT+01:00&#8243;</li>
<li>&#8220;my calendar: gregorian&#8221;</li>
<li>&#8220;my locale: it_IT&#8221;</li>
</ul>
<p>Ok, now let&#8217;s see how we can influence the formatter by changing locale and time zone:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// create an american locale</span><br />
NSLocale <span style="color: #339933;">*</span>usLocale <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSLocale alloc<span style="color: #009900;">&#93;</span> initWithLocaleIdentifier<span style="color: #339933;">:</span>@<span style="color: #ff0000;">&quot;en_US&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
<span style="color: #666666; font-style: italic;">// assign custom locale to the formatter</span><br />
<span style="color: #009900;">&#91;</span>formatter setLocale<span style="color: #339933;">:</span>usLocale<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #666666; font-style: italic;">// print formatted date</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;formatted date: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>formatter stringFromDate<span style="color: #339933;">:</span>currentDate<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>
Now it will print: &#8220;<strong>Saturday, 13 November 2010 &#8211; 12:10</strong>&#8221;  despite my system locale is &#8220;it_IT&#8221;.<br />
To influence date&#8217;s hours, I can set a different time zone rather than that one being used by my system:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// set a GMT time zone</span><br />
<span style="color: #009900;">&#91;</span>formatter setTimeZone<span style="color: #339933;">:</span><span style="color: #009900;">&#91;</span>NSTimeZone timeZoneWithAbbreviation<span style="color: #339933;">:</span>@<span style="color: #ff0000;">&quot;GMT&quot;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
<span style="color: #666666; font-style: italic;">// print formatted date</span><br />
NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;formatted date: %@&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>formatter stringFromDate<span style="color: #339933;">:</span>currentDate<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>
Now it will print: &#8220;<strong>Saturday, 13 November 2010 &#8211; 11:10</strong>&#8220;, in fact my system&#8217;s time zone is a &#8220;GMT+01:00&#8243; and if you subtract that +1 the result is 11 instead of 12!
</p>
<h3>Create an user defined date:</h3>
<p>
To create a custom date object (a date with an arbitrary year, month, day and so on), we have first to initialize an instance of <strong>NSDateComponents</strong> with the desired date&#8217;s parts and then use a calendar to retrieve the relative <strong>NSDate</strong>:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// create a custom dateComponents object</span><br />
NSDateComponents <span style="color: #339933;">*</span>customComponents <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSDateComponents alloc<span style="color: #009900;">&#93;</span> init<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#91;</span>customComponents setYear<span style="color: #339933;">:</span><span style="color: #0000dd;">2015</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#91;</span>customComponents setMonth<span style="color: #339933;">:</span><span style="color: #0000dd;">7</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#91;</span>customComponents setDay<span style="color: #339933;">:</span><span style="color: #0000dd;">23</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #666666; font-style: italic;">// create a date object using custom dateComponents against current calendar</span><br />
NSDate <span style="color: #339933;">*</span>customDate <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSCalendar currentCalendar<span style="color: #009900;">&#93;</span> dateFromComponents<span style="color: #339933;">:</span>customComponents<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<h3>Get date&#8217;s parts from a date</h3>
<p>
To extract date parts from an <strong>NSDate</strong> we have to use <strong>NSCalendar</strong>&#8216;s method <strong>components:fromDate:</strong>. Components are specified by a flag parameter which can be composed using the bitwise &#8220;or&#8221; operator (the pipe symbol) and merging <strong>NSCalendarUnit</strong> constants. To get year, month and day from a date we can do the following:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// get year, month and day parts</span><br />
NSDateComponents <span style="color: #339933;">*</span>components <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>calendar components<span style="color: #339933;">:</span><span style="color: #009900;">&#40;</span>NSYearCalendarUnit <span style="color: #339933;">|</span> NSMonthCalendarUnit <span style="color: #339933;">|</span> NSDayCalendarUnit<span style="color: #009900;">&#41;</span> fromDate<span style="color: #339933;">:</span>date<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>then we can use retrieved date parts in this way:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;year: %i - month: %i - day: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>components year<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>components month<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>components day<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>
It&#8217;s important to specify all the date parts we want to use, because if we forget it and we try to access an undefined part, we won&#8217;t get an error but instead <strong>2147483647</strong> as the return value (which is the maximum value for a signed 32-bit integer). For example if we write:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;hour: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>components hour<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>we will get <strong>2147483647</strong> because we didn&#8217;t specify the <strong>NSHourCalendarUnit</strong></p>
<h3>Add or subtract date parts from/to a date:</h3>
<p>
To add or subtract date parts from/to a date, we have to create a dateComponents object configuring it with the desired gap to fill and then use calendar&#8217;s method <strong>dateByAddingComponents:toDate:options:</strong>. For example if we want to add 2 years and half to a date we can do this:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #666666; font-style: italic;">// create a dateComponents with 2 years and 6 months</span><br />
NSDateComponents <span style="color: #339933;">*</span>newComponents <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSDateComponents alloc<span style="color: #009900;">&#93;</span> init<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#91;</span>newComponents setYear<span style="color: #339933;">:</span><span style="color: #0000dd;">2</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#91;</span>newComponents setMonth<span style="color: #339933;">:</span><span style="color: #0000dd;">6</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #666666; font-style: italic;">// get a new date by adding components</span><br />
NSDate <span style="color: #339933;">*</span>newDate <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSCalendar currentCalendar<span style="color: #009900;">&#93;</span> dateByAddingComponents<span style="color: #339933;">:</span>newComponents toDate<span style="color: #339933;">:</span>date options<span style="color: #339933;">:</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>
to subtract we have to configure <strong>NSDateComponents</strong> with negative values (ie: [newComponents setYear:-2]&#8230;)
</p>
<h3>Get difference between two dates:</h3>
<p>
To get the difference between 2 dates we have to rely on <strong>NSCalendar</strong> once again and use its <strong>components:fromDate:toDate</strong> method, by specifying the date parts we are interested in and 2 different dates. Values returned from components can be negative if toDate is earlier than fromDate. The following example retrieve days difference between 2 dates:
</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSDateComponents <span style="color: #339933;">*</span>componentsDiff <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>calendar components<span style="color: #339933;">:</span>NSDayCalendarUnit fromDate<span style="color: #339933;">:</span>dateA toDate<span style="color: #339933;">:</span>dateB options<span style="color: #339933;">:</span><span style="color: #0000dd;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<h2>Conclusion</h2>
<p>
Dates are a fascinating argument when it comes to programming in Objective C, but due to the different aspects involving date computation is really important to understand concepts beyond the mere classes implementations, especially if we want to make internationalized applications. My post would be a synthesis to help you get started faster with dates manipulation, I suggest however to read all the official documentation provided by Apple.</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2010/11/15/cocoa-objective-c-iphone-dates-objects/' addthis:title='Working with Cocoa dates objects ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncode.com/2010/11/15/cocoa-objective-c-iphone-dates-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>(My) common mistakes learning Objective C and iPhone programming</title>
		<link>http://www.daveoncode.com/2010/11/01/my-common-mistakes-learning-objective-c-and-iphone-programming/</link>
		<comments>http://www.daveoncode.com/2010/11/01/my-common-mistakes-learning-objective-c-and-iphone-programming/#comments</comments>
		<pubDate>Mon, 01 Nov 2010 14:15:21 +0000</pubDate>
		<dc:creator>Davide Zanotti</dc:creator>
				<category><![CDATA[Objective-c and Cocoa]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[uikit]]></category>

		<guid isPermaLink="false">http://www.daveoncode.com/?p=656</guid>
		<description><![CDATA[In this post I would like to gathering all the mistakes I did in the past months while I was learning Objective C, and although I&#8217;m still a learner and I will face new obstacles soon, I hope to keep in mind some concepts and language features better, by talking about those and help new [...]<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2010/11/01/my-common-mistakes-learning-objective-c-and-iphone-programming/' addthis:title='(My) common mistakes learning Objective C and iPhone programming ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to gathering all the mistakes I did in the past months while I was learning Objective C, and although I&#8217;m still a learner and I will face new obstacles soon, I hope to keep in mind some concepts and language features better, by talking about those and help new students save time on google and extra headache.<br />
So, let&#8217;s start with the errors list:</p>
<p><strong>1. No &#8220;foo&#8221; method found / &#8220;foo&#8221; may not respond to selector</strong></p>
<p>I was implementing a method (inside .m file) not defined before in the header (.h)</p>
<p><strong>2. Bad positioning and behavior of UITabBarController&#8217;s view</strong></p>
<p>I added the UITabBarController&#8217;s view to a subview rather than the main window (the only place where you can add it)</p>
<p><strong>3. Create my own null wrapper</strong></p>
<p>Objective C doesn&#8217;t allow nil values to be added to collections (NSArray, NSDictionary and so on) but just objects, so I got the smart idea of realize a dummy class representing null values. In this way I can create instances of &#8220;MyDummyNullObject&#8221; and add them to any kind of collection. However I successively discovered that Cocoa was already providing such class: <strong>NSNull</strong>! Moreover it offers a better implementation, because it&#8217;s a singleton, thus you don&#8217;t have to create more than one object but just relay on it&#8217;s &#8220;factory method&#8221;: <strong>[NSNull null]</strong> which will return the shared NSNull instance.</p>
<p><strong>4. Write repeated @synthetize statemens</strong></p>
<p>There is no need to write &#8220;@synthetize&#8221; for each class property, we can simple write it once followed by a comma delimited list of properties (ie: @synthetize prop1, prop2, prop3, prop3, prop4;)</p>
<p><strong>5. Create unnecessary pointers for scalar types</strong></p>
<p>Scalar types are basically all that is not a class (NSInteger, NSUInteger, BOOL&#8230;), for these types the asterisk is not required! (basically asterisk means: &#8220;I&#8217;m gonna to create a pointer to an instance of a class&#8221;)</p>
<p><strong>6. Try to compare strings and other objects by using == operator</strong></p>
<p>by using == we are not comparing strings values but pointers (which will be always different despite their content). The right way is using <strong>isEqualToString</strong>:, <strong>isEqual</strong>: or <strong>compare</strong>: (and its variants)</p>
<p><strong>7. Check sqlite&#8217;s database modifications in the wrong place</strong></p>
<p>I spent a lot of time to figure out why my insert and update commands did not modify database content, then I realized that I was looking at the wrong file! Project&#8217;s resources are copied during the build phase, and you can find them under:<br />
&#8220;/Users/$user_name/Library/Application Support/iPhone Simulator/$sdk_version/Applications/$app_id/$app_name.app&#8221; (of course you have to replace $foo with your personal info)</p>
<p><strong>8. Initialize variables inside switch/case statement</strong></p>
<p>Is not possible to initialize a variable as first declaration inside a case, if you try to compile the following code:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSNumber <span style="color: #339933;">*</span>number <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSNumber alloc<span style="color: #009900;">&#93;</span> initWithInt<span style="color: #339933;">:</span>value<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my number: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>number intValue<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>The compiler will rise an &#8220;Expected expression before NSNumber&#8221;. To avoid errors we can simply declare the instance variable before the switch statement in this way:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSNumber <span style="color: #339933;">*</span>number<span style="color: #339933;">;</span><br />
<br />
<span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; number <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSNumber alloc<span style="color: #009900;">&#93;</span> initWithInt<span style="color: #339933;">:</span>value<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my number: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>number intValue<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>or cheat the compiler by writing a command like an NSLog, before the assignment:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;go on without errors!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSNumber <span style="color: #339933;">*</span>number <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSNumber alloc<span style="color: #009900;">&#93;</span> initWithInt<span style="color: #339933;">:</span>value<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my number: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>number intValue<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>of course this last example is really nonsense, but it gives you the idea :)</p>
<p>UPDATE:<br />
As suggested by Dmitry Chestnykh in the comments, there is a better and easy approach to avoid such errors (pay attention to the curly braces in the case):</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #b1b100;">switch</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">case</span> <span style="color: #0000dd;">5</span><span style="color: #339933;">:</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSNumber <span style="color: #339933;">*</span>number <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSNumber alloc<span style="color: #009900;">&#93;</span> initWithInt<span style="color: #339933;">:</span>value<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; NSLog<span style="color: #009900;">&#40;</span>@<span style="color: #ff0000;">&quot;my number: %i&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span>number intValue<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #b1b100;">default</span><span style="color: #339933;">:</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p><strong>9. Unrecognized selector sent to instance</strong></p>
<p>I was declaring a pointer of type <strong>NSMutableArray</strong> and assigning it to an <strong>NSArray</strong> (a simple typo error), in this way:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">NSMutableArray <span style="color: #339933;">*</span>array <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#91;</span>NSArray alloc<span style="color: #009900;">&#93;</span> init<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>then I was filling it with &#8220;addObject&#8221;:</p>
<div class="codecolorer-container c mac-classic" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="c codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#91;</span>array addObject<span style="color: #339933;">:</span>myObject<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></div></td></tr></tbody></table></div>
<p>and at runtime I got the &#8220;unrecognized selector sent to instance&#8221;, this because I allocated an NSArray which doesn&#8217;t have &#8220;addObject&#8221; among its methods (in fact an NSArray is immutable and objects contained in this collection are specified during its creation)&#8230; anyway I don&#8217;t understand why the compiler does not rise an error at compile time :^/</p>
<p><strong>10. UITableViewCells mixed up after scrolling UITableView</strong></p>
<p>One of the most complex ui element to understand in the UiKit framework is undoubtedly UITableView, because it&#8217;s composed by different elements (like UITableViewCell) and requires a good knowledge of how it has been conceived in order to make it work the right way and with good performance. The main key concept behind this cool component resides in the method &#8220;<strong>tableView:cellForRowAtIndexPath</strong>&#8220;. The scope of this one is to return the <strong>UITableViewCell</strong> for a specific <strong>NSIndexPath</strong> and is called automatically at runtime. For performance reasons, it should returns cached objects by using <strong>dequeueReusableCellWithIdentifier</strong> and only if there is no a cached version (the method returns nil), initialize the required cell (that is allocating a UITableViewCell instance and configuring its views). In case of cached cells, you must avoid adding/removing views from the cell and limit changes to colors, label&#8217;s values and similar. Any other &#8220;invasive&#8221; change can results in strange table behavior and performance decrease.</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.daveoncode.com/2010/11/01/my-common-mistakes-learning-objective-c-and-iphone-programming/' addthis:title='(My) common mistakes learning Objective C and iPhone programming ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.daveoncode.com/2010/11/01/my-common-mistakes-learning-objective-c-and-iphone-programming/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

