<?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>Cocoanetics &#187; Q&amp;A</title>
	<atom:link href="http://www.cocoanetics.com/category/qa/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.cocoanetics.com</link>
	<description>Our DNA is written in Objective-C</description>
	<lastBuildDate>Fri, 03 Feb 2012 18:25:31 +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>iOS 5 Breaking NSDateFormatter?</title>
		<link>http://www.cocoanetics.com/2011/12/ios-5-breaking-nsdateformatter/</link>
		<comments>http://www.cocoanetics.com/2011/12/ios-5-breaking-nsdateformatter/#comments</comments>
		<pubDate>Fri, 23 Dec 2011 16:06:46 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5751</guid>
		<description><![CDATA[Robert Meraner asks: &#8220;Do you have any idea why this code works in iOS 4.3, but no longer under iOS 5? Googling it seems to turn up some ideas, but no immediate explanation.&#8221; This is the code Robert refers to: NSString *currentElementValue = @&#34;01.12.2011 09:35:13 CET&#34;; NSDateFormatter *dateFormatter = &#91;&#91;NSDateFormatter alloc&#93; init&#93;; &#91;dateFormatter setDateFormat:@&#34;dd.MM.yyyy HH:mm:ss zzz&#34;&#93;; NSDate *date = &#91;dateFormatter dateFromString:currentElementValue&#93;; This got me confounded initially as well, but thanks to Cédric Luthi we got an official answer to this riddle: works as intended! Label Buy an ad here Readability Trying out the above mentioned code you indeed find that date is correctly parsed on the 4.3 iPhone Simulator. If you simulate it on the 5.0 iPhone Simulator then you get a mysterious nil. NSDateFormatter has an NSLocale property to specify how text is output or &#8211; if you use it for parsing &#8211; is to be interpreted. So my first instinct was to try different locales because of the CET time zone abbreviation. Lo and behold, using en_GB did the trick. NSLocale *enLocale = &#91;&#91;NSLocale alloc&#93; initWithLocaleIdentifier:@&#34;en-GB&#34;&#93;; dateFormatter.locale = enLocale; &#91;enLocale release&#93;; I also checked which locale was used if you didn&#8217;t set the property and found that it defaulted to en-US. So apparently there was a change for this locale in iOS 5. Cédric had exactly the same problem and raised it with Apple. He was so kind as to share his Radar as well as the detailed response he got from an Apple engineer (emphasis mine): Engineering has determined that this issue behaves as intended based on the following information: This is an intentional change in iOS 5. The issue is this: With the short formats as specified by z (=zzz) or v (=vvv), there can be a lot of ambiguity. For example, &#8220;ET&#8221; for Eastern Time&#8221; could apply to different time zones in many different regions. To improve formatting and parsing reliability, the short forms are only used in a locale if the &#8220;cu&#8221; (commonly used) flag is set for the locale. Otherwise, only the long forms are used (for both formatting and parsing). This is a change in open-source CLDR 2.0 / ICU 4.8, which is the basis for the ICU in iOS 5, which in turn is the basis of NSDateFormatter behavior. For the &#8220;en&#8221; locale (= &#8220;en_US&#8221;), the cu flag is set for metazones such as Alaska, America_Central, America_Eastern, America_Mountain, America_Pacific, Atlantic, Hawaii_Aleutian, and GMT. It is not set for Europe_Central. However, for the &#8220;en_GB&#8221; locale, the cu flag is set for Europe_Central. So, a formatter set for short timezone style &#8220;z&#8221; or &#8220;zzz&#8221; and locale &#8220;en&#8221; or &#8220;en_US&#8221; will not parse &#8220;CEST&#8221; or &#8220;CET&#8221;, but if the locale is instead set to &#8220;en_GB&#8221; it will parse those. The &#8220;GMT&#8221; style will be parsed by all. If the formatter is set for the long timezone style &#8220;zzzz&#8221;, and the locale is any of &#8220;en&#8221;, &#8220;en_US&#8221;, or &#8220;en_GB&#8221;, then any of the following will be parsed, because they are unambiguous: &#8220;Pacific Daylight Time&#8221; &#8220;Central European Summer Time&#8221; &#8220;Central European Time&#8221; The mentioned ICU change (International Components for Unicode) is quite a mouthful, so we can be thankful that Apple is on top of what these Open Source guys are deciding and their engineers are merging all these locale fixes into our favorite operating system. In this special case we learn that it is not wise to use time zone abbreviations in server-generated XML. Better to have all dates use UTC with time zone &#8220;Z&#8221;. Alternatively you could use the UTC offset. This is never ambiguous. If you have no say in what comes from the server then the officially recommended locale that understands CET and CEST would be en_GB. You should always use the same locale to decode a date string as was used to encode it. The necessity for this would also be present if month names are spelled out or abbreviated in the source string. In short: Thou shalt not rely on the default locale to understand your date strings.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/ios-5-breaking-nsdateformatter/"></g:plusone></div><p>Robert Meraner asks:</p>
<p>&#8220;Do you have any idea why this code works in iOS 4.3, but no longer under iOS 5? Googling it seems to turn up some ideas, but no immediate explanation.&#8221;</p>
<p>This is the code Robert refers to:</p>

<div class="wp_codebox"><table><tr id="p57513"><td class="code" id="p5751code3"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>currentElementValue <span style="color: #002200;">=</span> <span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;01.12.2011 09:35:13 CET&quot;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/"><span style="color: #400080;">NSDateFormatter</span></a> <span style="color: #002200;">*</span>dateFormatter <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/"><span style="color: #400080;">NSDateFormatter</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>dateFormatter setDateFormat<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;dd.MM.yyyy HH:mm:ss zzz&quot;</span><span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/"><span style="color: #400080;">NSDate</span></a> <span style="color: #002200;">*</span>date <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>dateFormatter dateFromString<span style="color: #002200;">:</span>currentElementValue<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>This got me confounded initially as well, but thanks to <a href="http://www.cocoapedia.org/wiki/Cédric_Luthi">Cédric Luthi</a> we got an official answer to this riddle: works as intended!</p>
<p><span id="more-5751"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Trying out the above mentioned code you indeed find that date is correctly parsed on the 4.3 iPhone Simulator. If you simulate it on the 5.0 iPhone Simulator then you get a mysterious nil.</p>
<p>NSDateFormatter has an NSLocale property to specify how text is output or &#8211; if you use it for parsing &#8211; is to be interpreted. So my first instinct was to try different locales because of the CET time zone abbreviation.</p>
<p>Lo and behold, using en_GB did the trick.</p>

<div class="wp_codebox"><table><tr id="p57514"><td class="code" id="p5751code4"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/"><span style="color: #400080;">NSLocale</span></a> <span style="color: #002200;">*</span>enLocale <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/"><span style="color: #400080;">NSLocale</span></a> alloc<span style="color: #002200;">&#93;</span> initWithLocaleIdentifier<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;en-GB&quot;</span><span style="color: #002200;">&#93;</span>;
dateFormatter.locale <span style="color: #002200;">=</span> enLocale;
<span style="color: #002200;">&#91;</span>enLocale release<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>I also checked which locale was used if you didn&#8217;t set the property and found that it defaulted to en-US. So apparently there was a change for this locale in iOS 5.</p>
<p>Cédric had exactly the same problem and raised it with Apple. He was so kind as to share his <a href="http://www.openradar.me/9944011">Radar</a> as well as the detailed response he got from an Apple engineer (emphasis mine):</p>
<blockquote><p>Engineering has determined that this issue <strong>behaves as intended</strong> based on the following information:</p>
<p>This is an intentional change in iOS 5. The issue is this: With the short formats as specified by z (=zzz) or v (=vvv), there can be a lot of ambiguity. For example, &#8220;ET&#8221; for Eastern Time&#8221; could apply to different time zones in many different regions. To improve formatting and parsing reliability, the short forms are only used in a locale if the &#8220;cu&#8221; (commonly used) flag is set for the locale. Otherwise, only the long forms are used (for both formatting and parsing). This is a <strong>change in open-source CLDR 2.0 / ICU 4.8, which is the basis for the ICU in iOS 5</strong>, which in turn is the basis of NSDateFormatter behavior.</p>
<p>For the &#8220;en&#8221; locale (= &#8220;en_US&#8221;), the cu flag is set for metazones such as Alaska, America_Central, America_Eastern, America_Mountain, America_Pacific, Atlantic, Hawaii_Aleutian, and GMT. It is not set for Europe_Central.</p>
<p>However, for the &#8220;en_GB&#8221; locale, the cu flag is set for Europe_Central.</p>
<p>So, a formatter set for short timezone style &#8220;z&#8221; or &#8220;zzz&#8221; and locale &#8220;en&#8221; or &#8220;en_US&#8221; will not parse &#8220;CEST&#8221; or &#8220;CET&#8221;, but if the locale is instead set to &#8220;en_GB&#8221; it will parse those. The &#8220;GMT&#8221; style will be parsed by all.</p>
<p>If the formatter is set for the long timezone style &#8220;zzzz&#8221;, and the locale is any of &#8220;en&#8221;, &#8220;en_US&#8221;, or &#8220;en_GB&#8221;, then any of the following will be parsed, because they are unambiguous:</p>
<p>&#8220;Pacific Daylight Time&#8221; &#8220;Central European Summer Time&#8221; &#8220;Central European Time&#8221;</p></blockquote>
<p>The <a href="http://site.icu-project.org/download/48">mentioned ICU change</a> (International Components for Unicode) is quite a mouthful, so we can be thankful that Apple is on top of what these Open Source guys are deciding and their engineers are merging all these locale fixes into our favorite operating system.</p>
<p>In this special case we learn that it is not wise to use time zone abbreviations in server-generated XML. Better to have all dates use UTC with time zone &#8220;Z&#8221;. Alternatively you could use the UTC offset. This is never ambiguous.</p>
<p>If you have no say in what comes from the server then the officially recommended locale that understands CET and CEST would be en_GB. You should always use the same locale to decode a date string as was used to encode it. The necessity for this would also be present if month names are spelled out or abbreviated in the source string.</p>
<p>In short: Thou shalt not rely on the default locale to understand your date strings.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5751&amp;md5=07497cee99a86e9a0ce6018dd4843786" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/ios-5-breaking-nsdateformatter/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5751&amp;md5=07497cee99a86e9a0ce6018dd4843786" type="text/html" />"
	</item>
		<item>
		<title>Bit Masks</title>
		<link>http://www.cocoanetics.com/2011/12/bit-masks/</link>
		<comments>http://www.cocoanetics.com/2011/12/bit-masks/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 12:52:57 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5738</guid>
		<description><![CDATA[Joseph Collins asks: How do you decipher a bit mask from an argument which logically OR&#8217;d multiple values together? Enum uses bit shifting. This question came to me while looking at UIView&#8217;s header file and wondering how Apple handles the animation options bitmask. If you have several modes of something then usually you get by with an emum. But if you can combine several flags in s single value then you have to do this by means of bit masks. Let&#8217;s explore these today. Label Buy an ad here Readability An enum is basically just a number, an integer. But you are telling the compiler that the individual values are legal values. Internally the first value will be 0, the second will be 1 and so on. If you want the first value to be a different value you can specify this and you can even specify a different number for each value. If you don&#8217;t, then they are just numbered sequentially. Here&#8217;s an example from UIView.h: typedef enum &#123; UIViewAnimationCurveEaseInOut, // slow at beginning and end UIViewAnimationCurveEaseIn, // slow at beginning UIViewAnimationCurveEaseOut, // slow at end UIViewAnimationCurveLinear &#125; UIViewAnimationCurve; This defines UIViewAnimationCurveEaseInOut as 0 and the other values as 1, 2 and 3 using the automatic numbering. Often a developer chooses the default value to be the first because then a property using this type is also automatically initialized with the first value, aka 0. From the same header file we can glean another example. Still defined as an enum, but using a bit mask: enum &#123; UIViewAutoresizingNone = 0, UIViewAutoresizingFlexibleLeftMargin = 1 &#60;&#60; 0, UIViewAutoresizingFlexibleWidth = 1 &#60;&#60; 1, UIViewAutoresizingFlexibleRightMargin = 1 &#60;&#60; 2, UIViewAutoresizingFlexibleTopMargin = 1 &#60;&#60; 3, UIViewAutoresizingFlexibleHeight = 1 &#60;&#60; 4, UIViewAutoresizingFlexibleBottomMargin = 1 &#60;&#60; 5 &#125;; typedef NSUInteger UIViewAutoresizing; This is actually doing what I told you above, setting individual values for the numbers of the enum. The first value is 0, the second is a 1 bit shifted to the left by 0 positions, i.e. 1. The third value is a 1 bit shifted to the left by 1 positions, i.e. 2. The fourth is a 1 bit shifted to the left by 2 positions, i.e. 4. Get it it? They could have written out the numbers like this, but a geeky engineer preferred to write the values as shifts, number b One thing that tends to confuse people is the distinction between &#8220;logical&#8221; and &#8220;bitwise&#8221;.  You probably have used the logical operators quite a bit in if statements. Think of the bitwise cousins of essentially the same but not just for one and zero, but for all bits of a number. A logical NOT of 5 is 0, but a bitwise NOT of 5 (bin 101) is 2 (bin 010). To put it in simpler terms, a NOT flips all ones to zeros and vice versa. The AND and OR are twice the character for logical and once for bitwise. OR means that one of the bits needs to be one for the result to also be one. AND means that both need to be one for the result to be one. Remember that. To combine several values from a bit mask enum into one, you simply chain them together with the pipe symbol, which is the bitwise OR operator. Mathematically a bitwise OR is the same as an addition of the values, as long as they don&#8217;t overlap. view.autoresizingMask = UIViewAutoresizingFlexibleWidth&#124;UIViewAutoresizingFlexibleHeight; Now if you want to use a bit mask in your own code would involve the above mentioned type definitions as well as an if to check if certain bits of this mask are set. The simplest method I know is to basically make use of the logical AND. If the result is not equal to 0 &#8211; which it is if the bit was set &#8211; then we know that this bit was set. if &#40;view.autoresizingMask &#38; UIViewAutoresizingFlexibleWidth&#41; &#123; // bit was set &#125; You could also compare the result to != 0, greater than 0 or equal to the value you are checking for but personally I think that this version is the most readable. Let me repeat that bit masks only work if you have non-overlapping numbers in the enum. Each flag needs to be a distinct bit in the number, otherwise you end up with unexpected result. Adding values to it that are not single bits would set multiple flags at the same time. And then there&#8217;s the &#8220;pro&#8221; option. If you need to have more than a single bit on or off, but actually want to have an enum in and enum, there is also a way to do that as you can see in UIViewAnimationOptions. This is really weird to mentally parse if you are seeing that for the first time. enum &#123; UIViewAnimationOptionLayoutSubviews [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/bit-masks/"></g:plusone></div><p>Joseph Collins asks:</p>
<blockquote><p>How do you decipher a bit mask from an argument which logically OR&#8217;d multiple values together? Enum uses bit shifting.</p>
<p>This question came to me while looking at UIView&#8217;s header file and wondering how Apple handles the animation options bitmask.</p></blockquote>
<p>If you have several modes of something then usually you get by with an emum. But if you can combine several flags in s single value then you have to do this by means of bit masks. Let&#8217;s explore these today.</p>
<p><span id="more-5738"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>An enum is basically just a number, an integer. But you are telling the compiler that the individual values are legal values. Internally the first value will be 0, the second will be 1 and so on. If you want the first value to be a different value you can specify this and you can even specify a different number for each value. If you don&#8217;t, then they are just numbered sequentially.</p>
<p>Here&#8217;s an example from UIView.h:</p>

<div class="wp_codebox"><table><tr id="p573812"><td class="code" id="p5738code12"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">typedef</span> <span style="color: #a61390;">enum</span> <span style="color: #002200;">&#123;</span>
    UIViewAnimationCurveEaseInOut,         <span style="color: #11740a; font-style: italic;">// slow at beginning and end</span>
    UIViewAnimationCurveEaseIn,            <span style="color: #11740a; font-style: italic;">// slow at beginning</span>
    UIViewAnimationCurveEaseOut,           <span style="color: #11740a; font-style: italic;">// slow at end</span>
    UIViewAnimationCurveLinear
<span style="color: #002200;">&#125;</span> UIViewAnimationCurve;</pre></td></tr></table></div>

<p>This defines UIViewAnimationCurveEaseInOut as 0 and the other values as 1, 2 and 3 using the automatic numbering. Often a developer chooses the default value to be the first because then a property using this type is also automatically initialized with the first value, aka 0.</p>
<p>From the same header file we can glean another example. Still defined as an enum, but using a bit mask:</p>

<div class="wp_codebox"><table><tr id="p573813"><td class="code" id="p5738code13"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">enum</span> <span style="color: #002200;">&#123;</span>
    UIViewAutoresizingNone                 <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>,
    UIViewAutoresizingFlexibleLeftMargin   <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">0</span>,
    UIViewAutoresizingFlexibleWidth        <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">1</span>,
    UIViewAutoresizingFlexibleRightMargin  <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">2</span>,
    UIViewAutoresizingFlexibleTopMargin    <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">3</span>,
    UIViewAutoresizingFlexibleHeight       <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">4</span>,
    UIViewAutoresizingFlexibleBottomMargin <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">5</span>
<span style="color: #002200;">&#125;</span>;
<span style="color: #a61390;">typedef</span> NSUInteger UIViewAutoresizing;</pre></td></tr></table></div>

<p>This is actually doing what I told you above, setting individual values for the numbers of the enum. The first value is 0, the second is a 1 bit shifted to the left by 0 positions, i.e. 1. The third value is a 1 bit shifted to the left by 1 positions, i.e. 2. The fourth is a 1 bit shifted to the left by 2 positions, i.e. 4. Get it it? They could have written out the numbers like this, but a geeky engineer preferred to write the values as shifts, number << bits_to_shift.</p>
<p>There's another interesting fact to be seen there. Usually you would typedef an enum and call that type something of your own. Then you would use this type for defining your properties. Apple actually does not give the enum (typedef keyword omitted) a name. But actually they define a type UIViewAutoresizing to be an unsigned integer. Isn't that a bit weird because it breaks the compile-time type checking?</p>
<p>To understand working with bits we need to review a couple of operators in the C language.</p>
<ul>
<li>logical OR: a || b</li>
<li>logical NOT: !a</li>
<li>logical AND: a &amp;&amp; b</li>
<li>bitwise OR: a | v</li>
<li>bitwise NOT: ~a</li>
<li>bitwise AND:  a &amp; b</li>
<li>bitwise shift left: a << b</li>
<li>bitwise shift right:  a >> b</li>
</ul>
<p>One thing that tends to confuse people is the distinction between &#8220;logical&#8221; and &#8220;bitwise&#8221;.  You probably have used the logical operators quite a bit in if statements. Think of the bitwise cousins of essentially the same but not just for one and zero, but for all bits of a number. A logical NOT of 5 is 0, but a bitwise NOT of 5 (bin 101) is 2 (bin 010).</p>
<p>To put it in simpler terms, a NOT flips all ones to zeros and vice versa. The AND and OR are twice the character for logical and once for bitwise. OR means that one of the bits needs to be one for the result to also be one. AND means that both need to be one for the result to be one. Remember that.</p>
<p>To combine several values from a bit mask enum into one, you simply chain them together with the pipe symbol, which is the bitwise OR operator. Mathematically a bitwise OR is the same as an addition of the values, as long as they don&#8217;t overlap.</p>

<div class="wp_codebox"><table><tr id="p573814"><td class="code" id="p5738code14"><pre class="objc" style="font-family:monospace;">view.autoresizingMask <span style="color: #002200;">=</span> UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;</pre></td></tr></table></div>

<p>Now if you want to use a bit mask in your own code would involve the above mentioned type definitions as well as an if to check if certain bits of this mask are set. The simplest method I know is to basically make use of the logical AND. If the result is not equal to 0 &#8211; which it is if the bit was set &#8211; then we know that this bit was set.</p>

<div class="wp_codebox"><table><tr id="p573815"><td class="code" id="p5738code15"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>view.autoresizingMask <span style="color: #002200;">&amp;</span> UIViewAutoresizingFlexibleWidth<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
   <span style="color: #11740a; font-style: italic;">// bit was set</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You could also compare the result to != 0, greater than 0 or equal to the value you are checking for but personally I think that this version is the most readable. Let me repeat that bit masks only work if you have non-overlapping numbers in the enum. Each flag needs to be a distinct bit in the number, otherwise you end up with unexpected result. Adding values to it that are not single bits would set multiple flags at the same time.</p>
<p>And then there&#8217;s the &#8220;pro&#8221; option. If you need to have more than a single bit on or off, but actually want to have an enum in and enum, there is also a way to do that as you can see in UIViewAnimationOptions. This is really weird to mentally parse if you are seeing that for the first time.</p>

<div class="wp_codebox"><table><tr id="p573816"><td class="code" id="p5738code16"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">enum</span> <span style="color: #002200;">&#123;</span>
    UIViewAnimationOptionLayoutSubviews            <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">0</span>,
    UIViewAnimationOptionAllowUserInteraction      <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">1</span>, <span style="color: #11740a; font-style: italic;">// turn on user interaction while animating</span>
    UIViewAnimationOptionBeginFromCurrentState     <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">2</span>, <span style="color: #11740a; font-style: italic;">// start all views from current value, not initial value</span>
    UIViewAnimationOptionRepeat                    <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">3</span>, <span style="color: #11740a; font-style: italic;">// repeat animation indefinitely</span>
    UIViewAnimationOptionAutoreverse               <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">4</span>, <span style="color: #11740a; font-style: italic;">// if repeat, run animation back and forth</span>
    UIViewAnimationOptionOverrideInheritedDuration <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">5</span>, <span style="color: #11740a; font-style: italic;">// ignore nested duration</span>
    UIViewAnimationOptionOverrideInheritedCurve    <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">6</span>, <span style="color: #11740a; font-style: italic;">// ignore nested curve</span>
    UIViewAnimationOptionAllowAnimatedContent      <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">7</span>, <span style="color: #11740a; font-style: italic;">// animate contents (applies to transitions only)</span>
    UIViewAnimationOptionShowHideTransitionViews   <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt;  <span style="color: #2400d9;">8</span>, <span style="color: #11740a; font-style: italic;">// flip to/from hidden state instead of adding/removing</span>
&nbsp;
    UIViewAnimationOptionCurveEaseInOut            <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span> &lt;&lt; <span style="color: #2400d9;">16</span>, <span style="color: #11740a; font-style: italic;">// default</span>
    UIViewAnimationOptionCurveEaseIn               <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">16</span>,
    UIViewAnimationOptionCurveEaseOut              <span style="color: #002200;">=</span> <span style="color: #2400d9;">2</span> &lt;&lt; <span style="color: #2400d9;">16</span>,
    UIViewAnimationOptionCurveLinear               <span style="color: #002200;">=</span> <span style="color: #2400d9;">3</span> &lt;&lt; <span style="color: #2400d9;">16</span>,
&nbsp;
    UIViewAnimationOptionTransitionNone            <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span> &lt;&lt; <span style="color: #2400d9;">20</span>, <span style="color: #11740a; font-style: italic;">// default</span>
    UIViewAnimationOptionTransitionFlipFromLeft    <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionFlipFromRight   <span style="color: #002200;">=</span> <span style="color: #2400d9;">2</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionCurlUp          <span style="color: #002200;">=</span> <span style="color: #2400d9;">3</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionCurlDown        <span style="color: #002200;">=</span> <span style="color: #2400d9;">4</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionCrossDissolve   <span style="color: #002200;">=</span> <span style="color: #2400d9;">5</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionFlipFromTop     <span style="color: #002200;">=</span> <span style="color: #2400d9;">6</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
    UIViewAnimationOptionTransitionFlipFromBottom  <span style="color: #002200;">=</span> <span style="color: #2400d9;">7</span> &lt;&lt; <span style="color: #2400d9;">20</span>,
<span style="color: #002200;">&#125;</span>;
<span style="color: #a61390;">typedef</span> NSUInteger UIViewAnimationOptions;</pre></td></tr></table></div>

<p>I&#8217;m not dyslexic, but initially I thought &#8220;WTF are they doing shifting the number 20 (bin 10100) to the left?&#8221;. So you&#8217;re forgiven if you have the same reaction.</p>
<p>The first block is as we discussed before. The second and third block are actually more than single bits. You need two bits to represent the values 0 through 3. And three bits for 0 through 7. So here Apple is simply using the values and shifts them into place, 16 or 20 bits respectively. The advantage here is that a single animation options bit mask offers 32 bits that can be used. Packing the transition and the curve values into this still leaves with with a single integer to pass around. </p>
<p>Inside the UIKit code you probably have something like this, which shifts the values back to the right edge and then masks it and then compares.</p>

<div class="wp_codebox"><table><tr id="p573817"><td class="code" id="p5738code17"><pre class="objc" style="font-family:monospace;">NSUInteger transition <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>animationOption &gt;&gt; <span style="color: #2400d9;">20</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;</span> <span style="color: #2400d9;">7</span>;
NSUInteger curve <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>animationOption &gt;&gt; <span style="color: #2400d9;">16</span><span style="color: #002200;">&#41;</span> <span style="color: #002200;">&amp;</span> <span style="color: #2400d9;">3</span>;</pre></td></tr></table></div>

<p>The bitwise AND serves to mask out other set bits. Though if you are bit shifting the leftmost slot to the right, then the &#8220;incoming bits&#8221; are all zeroed anyway. But it&#8217;s probably a smart idea to make this masking a habit.</p>
<p>When creating your own bit masks I suggest that you name them in a similar way prefixing all enum values the same. This causes them to appear together in autocompletion and groups them logically.</p>
<p>Did you know you can actually also specify binary and hexadecimal values directly in your code? For hex numbers you add prefix 0x for binary prefix 0b. I heard that some compilers don&#8217;t know the binary prefix, but ours (LLVM) does. So if you EVER find yourself needing that you can use it. (You probably never will.)</p>

<div class="wp_codebox"><table><tr id="p573818"><td class="code" id="p5738code18"><pre class="objc" style="font-family:monospace;">NSUInteger b <span style="color: #002200;">=</span> 0b101; <span style="color: #11740a; font-style: italic;">// binary</span>
NSUInteger h <span style="color: #002200;">=</span> 0xAA; <span style="color: #11740a; font-style: italic;">// hex</span></pre></td></tr></table></div>

<p>If you only take one thing away from this article then it should be the distinction between &#8220;logical&#8221; and &#8220;bitwise&#8221;. Because then you would also know what is wrong in the original question. Can you spot it?</p>
<p><em>Image &#8220;bitmask {phantom of the opera}&#8221; by <a href="http://sadbots.com/comic/index.php?cid=7">S.D. Hilderbrand</a></em></p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5738&amp;md5=dd8f249f91bcec23bd0ffbb6c8f08609" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/bit-masks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5738&amp;md5=dd8f249f91bcec23bd0ffbb6c8f08609" type="text/html" />"
	</item>
		<item>
		<title>Coding Style</title>
		<link>http://www.cocoanetics.com/2011/12/coding-style/</link>
		<comments>http://www.cocoanetics.com/2011/12/coding-style/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 10:55:45 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5708</guid>
		<description><![CDATA[Dany asked: I&#8217;m looking at your (nice) project NSAttributedString-Additions-for-HTML and I have some questions about your convention of writing code. I really hope that you can reply to me, and maybe can be an idea for a future blog post (on naming conventions, and conventions in general for objective-c). I adopted several styles I read about in the coding style guides by Google and Marcus Zarra, though I have to admit I only skimmed through these and picket a couple of things that made sense. Though it is good practice to reflect on your style every once in a while to see if it still serves the purpose of making your code easier to maintain and read. Label Buy an ad here Readability Because there where several questions, let me alternate them and my answers: You sometime put @property on .m and not in .h, you do for private variables? if so why don&#8217;t use @private? A property is basically a shortcut to get a getter and setter method created for you. Getter-only if you specify readonly. Now for instance variables that are pointers to objects you probably want to retain these. So you specify the retain tag in the property definition. Such a retaining property releases the previous value and retains the new one, the standard implementation would look something like: @property &#40;nonatomic, retain&#41; NSObject *someObject; @synthesize someObject; &#160; // becomes: &#160; - &#40;void&#41;setSomeObject:&#40;NSObject *&#41;aObject &#123; if &#40;someObject != aObject&#41; // avoid release if no change &#123; &#91;someObject release&#93;; // release previous value someObject = &#91;aObject retain&#93;; // retain new value &#125; &#125; &#160; - &#40;NSObject *&#41;someObject &#123; return someObject; &#125; So having this ivar as a property saves me quite a bit of work with the release and retain. While that is more convenient for me, I don&#8217;t necessary want to expose all these values to outside callers. Because of that I moved the property definition into a private header extension which you can recognized by the empty category name in round brackets. This way the properties are being generated, but are not visible or callable from outside. Now with ARC that is not so much important any more because you don&#8217;t specify release or retain. So you can safely assume that this is sort of &#8220;Pre-ARC Style&#8221; and will go the way of the dodo bird. Sometime aren&#8217;t used @property at all, in which case exactly? I know that this just mean to use the iVar without getter\setter, but in which case you prefer to do it? A property for a scalar value (like NSInteger, CGFloat) does the same as using the ivar directly. So I never used properties for setting/getting those because it actually adds the overhead of a function call and return as opposed to accessing the value directly from within the class. Same question for methods prototype, you sometime put it in .m, you do this for private method? and so you keep only public method on .h? Exactly. If I have a method that I am encapsulating some functionality in that is to be called from several places inside the class code then I still want to hide that from the outside world. I see another thing that i don&#8217;t understand, you sometime write in your .h. why that? 2 property for the same iVar one with &#8220;readonly&#8221; in .h and the other without it in .m? @interface YourClass : NSObject &#123; NSArray *anArray; &#125; @property &#40;nonatomic, retain, readonly&#41; NSArray *anArray; &#160; and in .m @interface YourClass &#40;&#41; @property &#40;nonatomic, retain&#41; NSArray *anArray; @end This is the private class header extension (via anonymous category) I alluded to above. The synthesize generates a method to set the array but I only want that to be accessible from inside the .m implementation. Otherwise somebody would be able to mess with where the array ivar points to with possible unexpected consequences. You want to only allow outside callers access to the minimum amount of ivars and methods possible. Another question, you use the prefix _ only for some iVar. Why that? Is not preferable to have always or never? UIColor *_textColor; UIColor *backgroundColor; and then in .m @synthesize textColor = _textColor; @synthesize backgroundColor; You see me doing that if I am overwriting a property&#8217;s setter with my own code, probably because I want something else to be triggered when the property is used. For example with the textColor you might also want to call setNeedsDisplay on the view so that the text gets redrawn with the new color. I don&#8217;t like having to invent the name of the parameter for the setter with something preceding it with an a or an, but rather want the passed parameter to have the same name as the property. - &#40;void&#41;setTextColor:&#40;UIColor *&#41;aTextColor - &#40;void&#41;setTextColor:&#40;UIColor *&#41;textColor // better Now if the name of [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/12/coding-style/"></g:plusone></div><p>Dany asked:</p>
<blockquote><p>I&#8217;m looking at your (nice) project NSAttributedString-Additions-for-HTML and I have some questions about your convention of writing code.<br />
I really hope that you can reply to me, and maybe can be an idea for a future blog post (on naming conventions, and conventions in general for objective-c).</p></blockquote>
<p>I adopted several styles I read about in the coding style guides by <a href="http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml">Google</a> and <a href="http://www.cimgf.com/zds-code-style-guide/">Marcus Zarra</a>, though I have to admit I only skimmed through these and picket a couple of things that made sense.</p>
<p>Though it is good practice to reflect on your style every once in a while to see if it still serves the purpose of making your code easier to maintain and read.</p>
<p><span id="more-5708"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Because there where several questions, let me alternate them and my answers:</p>
<blockquote><p>You sometime put @property on .m and not in .h, you do for private variables? if so why don&#8217;t use @private?</p></blockquote>
<p>A property is basically a shortcut to get a getter and setter method created for you. Getter-only if you specify readonly. Now for instance variables that are pointers to objects you probably want to retain these. So you specify the retain tag in the property definition. Such a retaining property releases the previous value and retains the new one, the standard implementation would look something like:</p>

<div class="wp_codebox"><table><tr id="p570823"><td class="code" id="p5708code23"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a> <span style="color: #002200;">*</span>someObject;
<span style="color: #a61390;">@synthesize</span> someObject;
&nbsp;
<span style="color: #11740a; font-style: italic;">// becomes:</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setSomeObject<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>aObject
<span style="color: #002200;">&#123;</span>
   <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>someObject <span style="color: #002200;">!=</span> aObject<span style="color: #002200;">&#41;</span> <span style="color: #11740a; font-style: italic;">// avoid release if no change</span>
   <span style="color: #002200;">&#123;</span>
      <span style="color: #002200;">&#91;</span>someObject release<span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// release previous value</span>
      someObject <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>aObject retain<span style="color: #002200;">&#93;</span>; <span style="color: #11740a; font-style: italic;">// retain new value</span>
   <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>someObject
<span style="color: #002200;">&#123;</span>
   <span style="color: #a61390;">return</span> someObject;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>So having this ivar as a property saves me quite a bit of work with the release and retain. While that is more convenient for me, I don&#8217;t necessary want to expose all these values to outside callers. Because of that I moved the property definition into a private header extension which you can recognized by the empty category name in round brackets. This way the properties are being generated, but are not visible or callable from outside.</p>
<p>Now with ARC that is not so much important any more because you don&#8217;t specify release or retain. So you can safely assume that this is sort of &#8220;Pre-ARC Style&#8221; and will go the way of the dodo bird.</p>
<blockquote><p>Sometime aren&#8217;t used @property at all, in which case exactly? I know that this just mean to use the iVar without getter\setter, but in which case you prefer to do it?</p></blockquote>
<p>A property for a scalar value (like NSInteger, CGFloat) does the same as using the ivar directly. So I never used properties for setting/getting those because it actually adds the overhead of a function call and return as opposed to accessing the value directly from within the class.</p>
<blockquote><p>Same question for methods prototype, you sometime put it in .m, you do this for private method? and so you keep only public method on .h?</p></blockquote>
<p>Exactly. If I have a method that I am encapsulating some functionality in that is to be called from several places inside the class code then I still want to hide that from the outside world.</p>
<blockquote><p>I see another thing that i don&#8217;t understand, you sometime write in your .h. why that? 2 property for the same iVar one with &#8220;readonly&#8221; in .h and the other without it in .m?</p></blockquote>

<div class="wp_codebox"><table><tr id="p570824"><td class="code" id="p5708code24"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">@interface</span> YourClass <span style="color: #002200;">:</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSObject_Class/"><span style="color: #400080;">NSObject</span></a>
<span style="color: #002200;">&#123;</span>
   <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>anArray;
<span style="color: #002200;">&#125;</span>
<span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain, readonly<span style="color: #002200;">&#41;</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>anArray;
&nbsp;
and <span style="color: #a61390;">in</span> .m
<span style="color: #a61390;">@interface</span> YourClass <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>
   <span style="color: #a61390;">@property</span> <span style="color: #002200;">&#40;</span>nonatomic, retain<span style="color: #002200;">&#41;</span> <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> <span style="color: #002200;">*</span>anArray;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>This is the private class header extension (via anonymous category) I alluded to above. The synthesize generates a method to set the array but I only want that to be accessible from inside the .m implementation. Otherwise somebody would be able to mess with where the array ivar points to with possible unexpected consequences. You want to only allow outside callers access to the minimum amount of ivars and methods possible.</p>
<blockquote><p>Another question, you use the prefix _ only for some iVar. Why that? Is not preferable to have always or never?</p></blockquote>

<div class="wp_codebox"><table><tr id="p570825"><td class="code" id="p5708code25"><pre class="objc" style="font-family:monospace;">UIColor <span style="color: #002200;">*</span>_textColor;
UIColor <span style="color: #002200;">*</span>backgroundColor;
and then <span style="color: #a61390;">in</span> .m
<span style="color: #a61390;">@synthesize</span> textColor <span style="color: #002200;">=</span> _textColor;
<span style="color: #a61390;">@synthesize</span> backgroundColor;</pre></td></tr></table></div>

<p>You see me doing that if I am overwriting a property&#8217;s setter with my own code, probably because I want something else to be triggered when the property is used. For example with the textColor you might also want to call setNeedsDisplay on the view so that the text gets redrawn with the new color.</p>
<p>I don&#8217;t like having to invent the name of the parameter for the setter with something preceding it with an a or an, but rather want the passed parameter to have the same name as the property.</p>

<div class="wp_codebox"><table><tr id="p570826"><td class="code" id="p5708code26"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setTextColor<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIColor <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>aTextColor
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>setTextColor<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIColor <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>textColor <span style="color: #11740a; font-style: italic;">// better</span></pre></td></tr></table></div>

<p>Now if the name of the parameter is to be textColor then I have a problem inside this code block because the ivar has the same name. So how should the compiler know whether you mean textColor, the parameter or textColor, the ivar? Using the underscore prefix is the traditional method to have the ivar have a different name, but without messing up how it looks, because the small underscore does not hurt when reading the code.</p>
<blockquote><p>Last question (I hope): You sometime use @synthesize and sometime implement the setter\getter manually, you do that only to add some custom behavior, right? Like call a method if the variable change.</p></blockquote>
<p>That&#8217;s exactly the reason. If you have both a synthesize and a manual implementation of the setter method then the compiler will use manual implementation. I explained above how you sometimes need to trigger something when the setter is invoked.</p>
<h3>Conclusion</h3>
<p>Dany&#8217;s questions made me think about the use of properties in ARC-projects. Because you don&#8217;t need retain/release any more you probably also need to implement much fewer properties, even for internal use.</p>
<p>With the latest version of Apple&#8217;s LLVM compiler you also get another way of hiding unnecessary info from developers. You no longer need to define all ivars that are backing properties. Also you can now put the ivar definitions into the @implementation. But this possibility blew mind mind when I first heard about it. That&#8217;s crazy!</p>
<p>One reason why you DON&#8217;T want to hide everything is that you might restrict access to variables and member methods which are internal to the class too much. Like you would make it impossible for sub-classes to know about and access these. Remember that the .h file is also all that the child class knows about its super class.</p>
<p>If I have to come up with a rule for that:</p>
<ul>
<li>Hide external setters it if access by other developers breaks your class.</li>
<li>Don&#8217;t hide IVARs if you foresee that your class might be subclassed and these IVARs need to be accessible.</li>
</ul>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5708&amp;md5=939c560563a02d112b93a5232511ac89" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/12/coding-style/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5708&amp;md5=939c560563a02d112b93a5232511ac89" type="text/html" />"
	</item>
		<item>
		<title>Podcasts for iOS Developers</title>
		<link>http://www.cocoanetics.com/2011/09/podcasts-for-ios-developers/</link>
		<comments>http://www.cocoanetics.com/2011/09/podcasts-for-ios-developers/#comments</comments>
		<pubDate>Wed, 07 Sep 2011 08:59:08 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5401</guid>
		<description><![CDATA[I once dabbled a bit in podcasting myself with the Dr. Touch / Cocoanetics podcast, but I decided that I am not going to continue that on my own. I still like to TALK about it, if there&#8217;s somebody out there looking for a co-host &#8230; Whenever I walk the dog, doing chores or &#8220;grounding myself&#8221; while gardening I like to listen when experts in our industry are discussing latest developments that impact my professional live as iOS developer. So I asked on Twitter what your favorite related shows are and from the answers I made this list. And YES I checked it twice (several people were asking). Label Buy an ad here Readability These are your favorite podcasts related to iOS/Mac development and Apple in general. &#8220;Pretty much Everything from 5BY5&#8243; - 2 Votes Build and Analyze: 4 Votes &#8211; &#8220;Brilliant&#8221;, &#8220;It&#8217;s great!&#8221;, &#8220;Personal favorite&#8221; Listeners agree that host Marco Arment, founder of Instapaper, is a brilliant host and listening to him makes us all feel smarter. The Talkshow: Host John Gruber, Apple fanboy par excellence, discusses all around Apple. Hypercritical: John Siracusa of Ars Technica fame presents the critical view of Apple&#8217;s doings. NSBrief: &#8220;A brief podcast cast for Cocoa developers, talking about interesting developer-y stuff&#8221; &#8211; 2 Votes iDeveloper Live &#8211; 1 Vote IRQ Conflict: an interesting format: &#8220;Apple Developer. Microsoft Developer. FIGHT!&#8221; &#8211; 1 Vote We Have Communicators &#8211; 1 Vote Cocos2D Podcast: Indie Game Developer Steffen Itterheim talks about topics related to learning to use this game engine &#8211; 1 Vote There are two more shows that I myself like with a bit of a broader scope. Strangely I was the only one mentioning these, so it seems that 5BY5 has a way larger mindshare in developers than the well established TWIT network. This Week in Tech: Host Leo Laporte is a seasoned radio pro that manages to gather around tech journalists discussing the broader IT eco system we care about. MacBreak Weekly: The broadest opinion fest possible when it comes to Apple products. The third major network is Wizzard Media, providing several interesting feeds: Mac OS Ken: Host Ken Ray hosts this daily news show focussing on Mac and Apple news. Today in iOS: A very well made news podcast on the &#8220;latest happenings in the iPhone OS world&#8221; Also mentioned where these podcasts, either not updated in a while or hardly relevant: Core Intuition: last update in June - 1 Vote Cocoaheads.at Podcast (German) &#8211; 1 Vote Hamish &#38; Andy: an Australian Comedy Duo, no idea why it&#8217;s supposed to be of relevance to us &#8230; &#8211; 1 Vote If you feel that this list is incomplete please drop your suggestions in the comment box.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/09/podcasts-for-ios-developers/"></g:plusone></div><p>I once dabbled a bit in podcasting myself with the Dr. Touch / Cocoanetics podcast, but I decided that I am not going to continue that on my own. I still like to TALK about it, if there&#8217;s somebody out there looking for a co-host &#8230;</p>
<p>Whenever I walk the dog, doing chores or &#8220;grounding myself&#8221; while gardening I like to listen when experts in our industry are discussing latest developments that impact my professional live as iOS developer.</p>
<p>So I asked on Twitter what your favorite related shows are and from the answers I made this list. And YES I checked it twice (several people were asking).</p>
<p><span id="more-5401"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>These are your favorite podcasts related to iOS/Mac development and Apple in general.</p>
<ul>
<li><a href="http://5by5.tv/broadcasts">&#8220;Pretty much Everything from 5BY5&#8243;</a> - 2 Votes
<ul>
<li><a href="http://5by5.tv/buildanalyze">Build and Analyze</a>: 4 Votes &#8211; &#8220;Brilliant&#8221;, &#8220;It&#8217;s great!&#8221;, &#8220;Personal favorite&#8221;<br />
Listeners agree that host Marco Arment, founder of Instapaper, is a brilliant host and listening to him makes us all feel smarter.</li>
<li><a href="http://5by5.tv/talkshow">The Talkshow</a>: Host John Gruber, Apple fanboy par excellence, discusses all around Apple.</li>
<li><a href="http://5by5.tv/hypercritical">Hypercritical</a>: John Siracusa of Ars Technica fame presents the critical view of Apple&#8217;s doings.</li>
</ul>
</li>
<li><a href="http://nsbrief.com/">NSBrief</a>: &#8220;A brief podcast cast for Cocoa developers, talking about interesting developer-y stuff&#8221; &#8211; 2 Votes</li>
<li><a href="http://ideveloper.tv/shows">iDeveloper Live</a> &#8211; 1 Vote</li>
<li><a href="http://irqconflict.net/">IRQ Conflict</a>: an interesting format: &#8220;Apple Developer. Microsoft Developer. FIGHT!&#8221; &#8211; 1 Vote</li>
<li><a href="http://www.wehavecommunicators.com/">We Have Communicators</a> &#8211; 1 Vote</li>
<li><a href="http://www.learn-cocos2d.com/category/podcast/">Cocos2D Podcast</a>: Indie Game Developer Steffen Itterheim talks about topics related to learning to use this game engine &#8211; 1 Vote</li>
</ul>
<p>There are two more shows that I myself like with a bit of a broader scope. Strangely I was the only one mentioning these, so it seems that 5BY5 has a way larger mindshare in developers than the well established TWIT network.</p>
<div>
<ul>
<li><a href="http://twit.tv/show/this-week-in-tech">This Week in Tech</a>: Host Leo Laporte is a seasoned radio pro that manages to gather around tech journalists discussing the broader IT eco system we care about.</li>
<li><a href="http://twit.tv/show/macbreak-weekly">MacBreak Weekly</a>: The broadest opinion fest possible when it comes to Apple products.</li>
</ul>
<div>The third major network is Wizzard Media, providing several interesting feeds:</div>
<div>
<ul>
<li><a href="http://www.macosken.com">Mac OS Ken</a>: Host Ken Ray hosts this daily news show focussing on Mac and Apple news.</li>
<li><a href="http://tii.libsyn.com/">Today in iOS</a>: A very well made news podcast on the &#8220;latest happenings in the iPhone OS world&#8221;</li>
</ul>
</div>
</div>
<p>Also mentioned where these podcasts, either not updated in a while or hardly relevant:</p>
<ul>
<li><a href="http://www.coreint.org/">Core Intuition</a>: last update in June - 1 Vote</li>
<li><a href="http://cocoaheads.at/podcast">Cocoaheads.at Podcast</a> (German) &#8211; 1 Vote</li>
<li><a href="http://www.hamishandandy.com/">Hamish &amp; Andy</a>: an Australian Comedy Duo, no idea why it&#8217;s supposed to be of relevance to us &#8230; &#8211; 1 Vote</li>
</ul>
<div>If you feel that this list is incomplete please drop your suggestions in the comment box.</div>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5401&amp;md5=3889532586e8b3bf9ca1427f2df7473c" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/09/podcasts-for-ios-developers/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5401&amp;md5=3889532586e8b3bf9ca1427f2df7473c" type="text/html" />"
	</item>
		<item>
		<title>NSAttributedString+HTML Q&amp;A</title>
		<link>http://www.cocoanetics.com/2011/08/nsattributedstringhtml-qa/</link>
		<comments>http://www.cocoanetics.com/2011/08/nsattributedstringhtml-qa/#comments</comments>
		<pubDate>Wed, 31 Aug 2011 08:02:18 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5373</guid>
		<description><![CDATA[Over the past few months I have received questions about NSAttributedString+HTML and Rich Text Editing. Here are the Frequently Asked Questions. I generally abbreviate NSAttributedString+HTML as NSAS+HTML. If your question or app is not in this list please let me know. Label Buy an ad here Readability General / Cost / Licensing What is NSAS+HTML? Cocoa on the Mac has an initWithHTML method on NSAttributedString. NSAS+HTML consists of 3 parts: A reverse-engineered and enhanced implementation of the Mac initWithHTML for use on iOS UI classes to properly render the created NSAttributedString Objective-C wrapper classes for CoreText to simplify it&#8217;s use The goal of NSAS+HTML is to provide a comprehensive way to eliminate UIWebViews from your apps and reap the benefits of being able to fully control the way the rich text is rendered and how your users interact with it. Where does it live? How do you contribute to it? NSAS+HTML is hosted on GitHub. If you find problems then please open an issue there. If you fix a problem or add a new feature then you can send a pull request so that the modifications from your fork can be merged into the master repository. Does NSAS+HTML contain private APIs? No. All code was newly created by the original author Oliver Drobnik as well as several contributors. NSAS+HTML is not a web browser, but instead renders views described with HTML. Is NSAS+HTML legal to be used in App Store Apps? Yes. A growing number of apps is using NSAS+HTML, the examples I know about are: APODViewer and APODViewer HD Float Reader (Making Of) SOStacked Russ.No Please let me know if your app is not in this list so that I can add it. How is NSAS+HTML licensed? NSAttributedString+HTML is licensed under a BSD license. This means that you can use it for free in free and commercial products as long as you mention in the app that it contains &#8220;NSAttributedString+HTML copyright by Oliver Drobnik / Cocoanetics&#8221;. Binary apps must display such a copyright notice somewhere accessible to the user, for example in the settings or about page. Source code apps must contain the license text file that is part of the GitHub project. Is there a way to use NSAS+HTML without attributing it? Yes. You can purchase a non-attribution license for €75 for it that eliminates the need for the attribution while still being able to use it in your commercial and free apps. Does NSAS+HTML support Rich Text Editing? No. By itself NSAS+HTML only renders. A commercial component of mine, called DTRichTextEditor, builds on it and adds text input. What is the difference between DTAttributedTextView and DTAttributedTextContentView? DTAttributedTextView is a scrollview sub class that has a DTAttributedTextContentView as sole sub view. DTAttributedTextContentView sizes itself to automatically fit the text. Fonts What is the default font? Times New Roman, 12 px. If you don&#8217;t specify any font attributes in the HTML this will be the font that is used. Headers are sized relative to that. How do you change the default font size on DTAttributedTextView? You can pass a dictionary with a variety of parameters to initWithHTML. One of these parameters is NSTextSizeMultiplierDocumentOption the text scale that causes all fonts to be a multiple of what their default would be. This affects all headers and body text equally. Why does the first time attributed text is shown take 1 sec? This is a bug in iOS that causes an extensive font matching table to be created the first time a CTFont is required. You have two possible workarounds available: Pre-initialize CoreText as shown here on a background thread. Put all the fonts you require in CoreTextFontOverrides.plist If you only using one font then number 2 is the recommended method since it bypasses CoreText font matching. What is the difference between Font, Font Face, Font Family and Font Variant? A font family is the overall grouping of multiple fonts. Each font represents one look, like plain or bold. Font and Font Face are the same. Font is often used incorrectly synonymous with Font Family. For example the Helvetica font family consists of these fonts/faces: Helvetica Helvetica-Bold Helvetica-Oblique Helvetica-BoldOblique When NSAS+HTML requires a font face from a given family with a given size it will first look into the overrides plist (if present) and then use CoreText font matching. Font Variants are different representations contained within the same font file/face. For example on iPad there is one font that contains also a small caps variant. A bold font is NOT a variant, it is a font in its own right. Implementation How can DTAttributedTextView be used in table view cells? DTAttributedTextView should not be used in table view cells because it is a scrollview. You can either use DTAttributedTextContentView and use their automatically sized heights for the heightForRowAtIndexPath or use the specially created DTAttributedTextCell class for that [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/08/nsattributedstringhtml-qa/"></g:plusone></div><p>Over the past few months I have received questions about NSAttributedString+HTML and Rich Text Editing. Here are the <span style="text-decoration: underline;">Frequently Asked Questions</span>.</p>
<p>I generally abbreviate NSAttributedString+HTML as NSAS+HTML. If your question or app is not in this list please let me know.</p>
<p><span id="more-5373"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<h2>General / Cost / Licensing</h2>
<h3>What is NSAS+HTML?</h3>
<p>Cocoa on the Mac has an initWithHTML method on NSAttributedString. NSAS+HTML consists of 3 parts:</p>
<ol>
<li>A reverse-engineered and enhanced implementation of the Mac initWithHTML for use on iOS</li>
<li>UI classes to properly render the created NSAttributedString</li>
<li>Objective-C wrapper classes for CoreText to simplify it&#8217;s use</li>
</ol>
<p>The goal of NSAS+HTML is to provide a comprehensive way to <a title="UIWebView must die" href="http://www.cocoanetics.com/2011/01/uiwebview-must-die/">eliminate UIWebViews</a> from your apps and reap the benefits of being able to fully control the way the rich text is rendered and how your users interact with it.</p>
<h3>Where does it live? How do you contribute to it?</h3>
<p>NSAS+HTML is <a href="https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML">hosted on GitHub</a>. If you find problems then please <a href="https://github.com/Cocoanetics/NSAttributedString-Additions-for-HTML/issues">open an issue</a> there. If you fix a problem or add a new feature then you can send a <a title="Back … and Many News" href="http://www.cocoanetics.com/2011/08/back-and-many-news/">pull request</a> so that the modifications from your fork can be merged into the master repository.</p>
<h3>Does NSAS+HTML contain private APIs?</h3>
<p>No. All code was newly created by the original author <a href="http://www.cocoapedia.org/wiki/Oliver_Drobnik">Oliver Drobnik</a> as well as several contributors. NSAS+HTML is not a web browser, but instead renders views described with HTML.</p>
<h3>Is NSAS+HTML legal to be used in App Store Apps?</h3>
<p>Yes. A growing number of apps is using NSAS+HTML, the examples I know about are:</p>
<ul>
<li><a href="http://itunes.apple.com/app/apodviewer-astronomy-picture/id292538105?mt=8">APODViewer</a> and <a href="http://itunes.apple.com/app/apodviewerhd-astronomy-picture/id407493364?mt=8">APODViewer HD</a></li>
<li><a href="http://itunes.apple.com/us/app/float-reader/id447992005?mt=8">Float Reader</a> (<a title="Start Floating" href="http://www.cocoanetics.com/2011/07/start-floating/">Making Of</a>)</li>
<li><a href="http://itunes.apple.com/at/app/sostacked/id427708024?mt=8">SOStacked</a></li>
<li><a href="http://itunes.apple.com/no/app/russ.no/id457972151?mt=8">Russ.No</a></li>
</ul>
<p>Please let me know if your app is not in this list so that I can add it.</p>
<h3>How is NSAS+HTML licensed?</h3>
<p>NSAttributedString+HTML is licensed under a <span style="text-decoration: underline;">BSD license</span>. This means that you can use it for free in free and commercial products as long as you mention in the app that it contains &#8220;NSAttributedString+HTML copyright by Oliver Drobnik / Cocoanetics&#8221;.</p>
<p>Binary apps must display such a copyright notice somewhere accessible to the user, for example in the settings or about page. Source code apps must contain the license text file that is part of the GitHub project.</p>
<h3>Is there a way to use NSAS+HTML without attributing it?</h3>
<p>Yes. You can purchase a <a href="mailto:oliver@cocoanetics.com?subject=NSAttributedString+HTML%20Non-Attribution%20License&amp;body=I%20want%20to%20order%20a%20non-attribution%20license%20for%20this%20component.%0A%0AName%20of%20Company%20or%20Individual:%0A%0AInvoice%20Address:%0A%0A%0AEU%20VAT%20ID%20(if%20applicable):%0A%0A">non-attribution license</a> for €75 for it that eliminates the need for the attribution while still being able to use it in your commercial and free apps.</p>
<h3>Does NSAS+HTML support Rich Text Editing?</h3>
<p>No. By itself NSAS+HTML only renders. A commercial component of mine, called <a href="http://www.cocoanetics.com/parts/dtrichtexteditor/">DTRichTextEditor</a>, builds on it and adds text input.</p>
<h3>What is the difference between DTAttributedTextView and DTAttributedTextContentView?</h3>
<p>DTAttributedTextView is a scrollview sub class that has a DTAttributedTextContentView as sole sub view. DTAttributedTextContentView sizes itself to automatically fit the text.</p>
<h2>Fonts</h2>
<h3>What is the default font?</h3>
<p>Times New Roman, 12 px. If you don&#8217;t specify any font attributes in the HTML this will be the font that is used. Headers are sized relative to that.</p>
<h3>How do you change the default font size on DTAttributedTextView?</h3>
<p>You can pass a dictionary with a variety of parameters to initWithHTML. One of these parameters is NSTextSizeMultiplierDocumentOption the text scale that causes all fonts to be a multiple of what their default would be. This affects all headers and body text equally.</p>
<h3>Why does the first time attributed text is shown take 1 sec?</h3>
<p>This is a bug in iOS that causes an extensive font matching table to be created the first time a CTFont is required. You have two possible workarounds available:</p>
<ol>
<li>Pre-initialize CoreText as <a title="CoreText Loading Performance" href="http://www.cocoanetics.com/2011/04/coretext-loading-performance/">shown here</a> on a background thread.</li>
<li>Put all the fonts you require in CoreTextFontOverrides.plist</li>
</ol>
<p>If you only using one font then number 2 is the recommended method since it bypasses CoreText font matching.</p>
<h3>What is the difference between Font, Font Face, Font Family and Font Variant?</h3>
<p>A font family is the overall grouping of multiple fonts. Each font represents one look, like plain or bold. Font and Font Face are the same. Font is often used incorrectly synonymous with Font Family.</p>
<p>For example the Helvetica font family consists of these fonts/faces:</p>
<ul>
<li>Helvetica</li>
<li>Helvetica-Bold</li>
<li>Helvetica-Oblique</li>
<li>Helvetica-BoldOblique</li>
</ul>
<p>When NSAS+HTML requires a font face from a given family with a given size it will first look into the overrides plist (if present) and then use CoreText font matching.</p>
<p>Font Variants are different representations contained within the same font file/face. For example on iPad there is one font that contains also a small caps variant. A bold font is NOT a variant, it is a font in its own right.</p>
<h2>Implementation</h2>
<p><span class="Apple-style-span" style="font-size: 15px; font-weight: bold;">How can DTAttributedTextView be used in table view cells?</span></p>
<p>DTAttributedTextView should not be used in table view cells because it is a scrollview. You can either use DTAttributedTextContentView and use their automatically sized heights for the heightForRowAtIndexPath or use the specially created DTAttributedTextCell class for that purpose. Please refer to DemoSnippetsViewController.m to see how it is used.</p>
<p>Please note that if you are using a different height for each row this dramatically reduces table view scrolling performance. Instead we recommend to use a fixed height.</p>
<h3>After implementing DTAttributedTextView URLs show up but cannot be clicked, why?</h3>
<p>NSAS+HTML is only in charge of rendering the text, you have to take care of the interactivity because everybody might have different needs.</p>
<p>NSAS+HTML provides delegate methods asking for custom subviews to be put over links. You can use the DTLinkButton provided with NSAS+HTML and have this perform any action you like.</p>
<h3>What is DTTextAttachment?</h3>
<p>DTTextAttachment encapsulates any kind of object that the layout process should reserve space for. This could be an image or a video. The space that is reserved for displaying this is taken from the displaySize property.</p>
<h3>How are images rendered?</h3>
<p>NSAS+HTML has two built in methods to render images. Either you enable the shouldDrawImages property on the content view which will draw local images together with the text. Or you implement the delegate method to provide your own UIView to show the contents of the DTTextAttachment that encapsulates the image.</p>
<p>For local images the contents property of the attachment contains the UIImage, for remote images the contentURL provides the URL for lazy loading. NSAS+HTML provides DTLazyImageView which demonstrates how to lazily load images from remote URLs, please refer to DemoTextViewController.m to see how this is integrated.</p>
<p>Note that you have to trigger a re-layout once you have loaded a remote image as soon as the actually displaySize of the DTTextAttachment is known. This step is not necessary if you specify a width/height in the HTML tag because then the displaySize of the attachment is known for layouting.</p>
<h3>Does NSAS+HTML support Floating of Images?</h3>
<p>No. Floating allows images to be positioned on the left or right side of the document and have text flow around them. Currently layouting is done in a single pass with one layout frame. To support floating of text attachments multiple passes would be required to determine the optimal sizing of multiple rectangles to be filled with text.</p>
<h3>Does NSAS+HTML support multiple column layout?</h3>
<p>Yes and No. The provided UI classes only work with a single layout frame.</p>
<p>To get multiple column layout you have to create your own UIView that takes multiple layout frames. The steps are:</p>
<ol>
<li>Create your DTCoreTextLayouter from the attributed string.</li>
<li>Create a DTCoreTextLayoutFrame for the first column specifying the rectangle</li>
<li>Create a second layout frame for the second column specifying another rectangle and the starting index that is one higher than the ending index in the first column</li>
<li>Repeat this for each column</li>
</ol>
<p>Once you have all these layout frames your UIView subclass only needs to call renderInContext for all columns.</p>
<h3>Does NSAS+HTML support CSS styles sheets?</h3>
<p>Not yet, but some contributors are working on this. At present only styles that are contained in the individual tags are recognized.</p>
<h3>Does NSAS+HTML also allow for creating HTML out of attributed strings?</h3>
<p>Yes. There is a htmlString method in the HTML category. This needs much work still.</p>
<h3>Does NSAS+HTML support Margin or Padding?</h3>
<p>No. Those are attributes that require the distribute the text into multiple blocks. There is no block level support in NSAS, essentially one layout frame is one big block.</p>
<p>You can specify edgeInsets on all sides for  DTAttributedTextContentView which considers this inset on sizing the layout frame.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5373&amp;md5=846912a2576c959d5d5e5c9a7f01f040" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/08/nsattributedstringhtml-qa/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5373&amp;md5=846912a2576c959d5d5e5c9a7f01f040" type="text/html" />"
	</item>
		<item>
		<title>Adding Fading Gradients to UITableView</title>
		<link>http://www.cocoanetics.com/2011/08/adding-fading-gradients-to-uitableview/</link>
		<comments>http://www.cocoanetics.com/2011/08/adding-fading-gradients-to-uitableview/#comments</comments>
		<pubDate>Fri, 26 Aug 2011 08:22:37 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5347</guid>
		<description><![CDATA[Jason Jardim asked (4 Months ago): This is just a screen shot I found with someone posting a similar question.  I am trying to fade out he top/ bottom cells in a tableview. How do I achieve this effect? First of all, Jason, I am sorry it took so long. I was extremely busy during the past few months but I kept your e-mail at the bottom of my inbox as something that I am really interested in to give a good answer to. Let me make it up for you by proposing several solutions to your question as well as show one that I find the coolest. Label Buy an ad here Readability First of all by looking at the sample screenshot we see that there is a border around the table view. This tells us that the table view does not fill the entire screen but there is obviously an imageView responsible for the ornamentals surrounding the table view. If we go with this imageView then the next question is whether the image is below or above the table view itself. The first instinct might be &#8220;below!&#8221; but that can be treacherous and cause you more work than is actually needed to achieve this effect. You could just as well have the part for the table view &#8220;cut out&#8221; in the image, i.e. have the center portion be Alpha 0 and the top and bottom would be an alpha gradient from 100% to 0%. A designer versed with Photoshop could easily create something like this for you. Then you put this imageView on top of your table view, size the table view to fit inside the border. Finally you will want to make sure that userInteraction is disabled on the imageView, because otherwise no touches would be reaching the table view. While this solution is simple it does not satisfy me personally. As developer I want to achieve such an effect entirely in code because then it has the added advantage of being independent or resolution or interface orientation. The first thing we&#8217;ll try is to mask the layer of the table view. On iOS each UIView has a CALayer that takes care of the actual drawing. And each CALayer has a mask property where you can set another layer to mask out parts of the host layer. For masking layers it does not matter which colors you use because only the alpha value of each pixel is considered for the composition. 100% alpha means that a layer pixel shows fully, 0% alpha causes a layer pixel to be transparent. For this tutorial I created a new navigation-based app without CoreData. We also need the QuartzCore.framework for the advanced layer handling methods. A useful layer type for this purpose is CAGradientLayer which exists since iOS version 3.0. RootViewController.h #import &#60;UIKit/UIKit.h&#62; #import &#60;QuartzCore/QuartzCore.h&#62; &#160; @interface RootViewController : UITableViewController &#123; CAGradientLayer *maskLayer; &#125; &#160; @end For the sake of simplicity we create the mask in viewWillAppear because at this point the table view has already been resized to the proper size. If we would create it earlier (or if you plan to support different sizes) then you would also need code to adjust the layer bounds to fit. - &#40;void&#41;viewWillAppear:&#40;BOOL&#41;animated &#123; &#91;super viewWillAppear:animated&#93;; &#160; if &#40;!maskLayer&#41; &#123; maskLayer = &#91;CAGradientLayer layer&#93;; &#160; CGColorRef outerColor = &#91;UIColor colorWithWhite:1.0 alpha:0.0&#93;.CGColor; CGColorRef innerColor = &#91;UIColor colorWithWhite:1.0 alpha:1.0&#93;.CGColor; &#160; maskLayer.colors = &#91;NSArray arrayWithObjects:&#40;id&#41;outerColor, &#40;id&#41;innerColor, &#40;id&#41;innerColor, &#40;id&#41;outerColor, nil&#93;; maskLayer.locations = &#91;NSArray arrayWithObjects:&#91;NSNumber numberWithFloat:0.0&#93;, &#91;NSNumber numberWithFloat:0.2&#93;, &#91;NSNumber numberWithFloat:0.8&#93;, &#91;NSNumber numberWithFloat:1.0&#93;, nil&#93;; &#160; maskLayer.bounds = CGRectMake&#40;0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height&#41;; maskLayer.anchorPoint = CGPointZero; &#160; self.view.layer.mask = maskLayer; &#125; &#125; We only create the layer once. Since there can be only one mask layer at a time we combine the top and the bottom gradient into one where the outer areas will be 20% of the entire height. The default anchor point is the center of the layer, so we change that to the top left. If we stopped here then you would get the gradients, but they would move together with the contents of the table view. Luckily table views are UIScrollView child classes and thus you can also implement the UIScrollViewDelegate methods. We are using the one that fires on each movement to adjust the position of the masking layer. - &#40;void&#41;scrollViewDidScroll:&#40;UIScrollView *&#41;scrollView &#123; &#91;CATransaction begin&#93;; &#91;CATransaction setDisableActions:YES&#93;; maskLayer.position = CGPointMake&#40;0, scrollView.contentOffset.y&#41;; &#91;CATransaction commit&#93;; &#125; Note that we also need to disable actions because position is an animatable property on CALayer. If you set that this triggers an implicit animation which would cause the masking layer to lag behind. With actions disabled the layer position is set right away. There&#8217;s another problem that only becomes apparent if you start scrolling and the vertical scroll bar shows: it is also affected by the mask which you probably don&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/08/adding-fading-gradients-to-uitableview/"></g:plusone></div><p>Jason Jardim asked (4 Months ago):</p>
<blockquote><p>This is just a screen shot I found with someone posting a similar question.  I am trying to fade out he top/ bottom cells in a tableview. How do I achieve this effect?</p></blockquote>
<p>First of all, Jason, I am sorry it took so long. I was extremely busy during the past few months but I kept your e-mail at the bottom of my inbox as something that I am really interested in to give a good answer to.</p>
<p>Let me make it up for you by proposing several solutions to your question as well as show one that I find the coolest.</p>
<p><span id="more-5347"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>First of all by looking at the sample screenshot we see that there is a border around the table view. This tells us that the table view does not fill the entire screen but there is obviously an imageView responsible for the ornamentals surrounding the table view.</p>
<p><a href="http://www.cocoanetics.com/files/StGyg.png"><img class="alignnone size-medium wp-image-5348" title="Faded out top and bottom tableview cells" src="http://www.cocoanetics.com/files/StGyg-193x300.png" alt="" width="193" height="300" /></a></p>
<p>If we go with this imageView then the next question is whether the image is below or above the table view itself. The first instinct might be &#8220;below!&#8221; but that can be treacherous and cause you more work than is actually needed to achieve this effect. You could just as well have the part for the table view &#8220;cut out&#8221; in the image, i.e. have the center portion be Alpha 0 and the top and bottom would be an alpha gradient from 100% to 0%.</p>
<p>A designer versed with Photoshop could easily create something like this for you. Then you put this imageView on top of your table view, size the table view to fit inside the border. Finally you will want to make sure that userInteraction is disabled on the imageView, because otherwise no touches would be reaching the table view.</p>
<p>While this solution is simple it does not satisfy me personally. As developer I want to achieve such an effect entirely in code because then it has the added advantage of being independent or resolution or interface orientation.</p>
<p>The first thing we&#8217;ll try is to mask the layer of the table view. On iOS each UIView has a CALayer that takes care of the actual drawing. And each CALayer has a mask property where you can set another layer to mask out parts of the host layer.</p>
<p>For masking layers it does not matter which colors you use because only the alpha value of each pixel is considered for the composition. 100% alpha means that a layer pixel shows fully, 0% alpha causes a layer pixel to be transparent.</p>
<p>For this tutorial I created a new navigation-based app without CoreData. We also need the QuartzCore.framework for the advanced layer handling methods. A useful layer type for this purpose is CAGradientLayer which exists since iOS version 3.0.</p>
<p><strong>RootViewController.h</strong></p>

<div class="wp_codebox"><table><tr id="p534731"><td class="code" id="p5347code31"><pre class="objc" style="font-family:monospace;"><span style="color: #6e371a;">#import &lt;UIKit/UIKit.h&gt;</span>
<span style="color: #6e371a;">#import &lt;QuartzCore/QuartzCore.h&gt;</span>
&nbsp;
<span style="color: #a61390;">@interface</span> RootViewController <span style="color: #002200;">:</span> UITableViewController
<span style="color: #002200;">&#123;</span>
    CAGradientLayer <span style="color: #002200;">*</span>maskLayer;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #a61390;">@end</span></pre></td></tr></table></div>

<p>For the sake of simplicity we create the mask in viewWillAppear because at this point the table view has already been resized to the proper size. If we would create it earlier (or if you plan to support different sizes) then you would also need code to adjust the layer bounds to fit.</p>

<div class="wp_codebox"><table><tr id="p534732"><td class="code" id="p5347code32"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewWillAppear<span style="color: #002200;">:</span>animated<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>maskLayer<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        maskLayer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CAGradientLayer layer<span style="color: #002200;">&#93;</span>;
&nbsp;
        CGColorRef outerColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span> alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#93;</span>.CGColor;
        CGColorRef innerColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span> alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>.CGColor;
&nbsp;
        maskLayer.colors <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>outerColor, 
                            <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>innerColor, <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>innerColor, <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>outerColor, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
        maskLayer.locations <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.2</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.8</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        maskLayer.bounds <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>,
                            self.tableView.frame.size.width,
                            self.tableView.frame.size.height<span style="color: #002200;">&#41;</span>;
        maskLayer.anchorPoint <span style="color: #002200;">=</span> CGPointZero;
&nbsp;
       self.view.layer.mask <span style="color: #002200;">=</span> maskLayer;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>We only create the layer once. Since there can be only one mask layer at a time we combine the top and the bottom gradient into one where the outer areas will be 20% of the entire height. The default anchor point is the center of the layer, so we change that to the top left.</p>
<p>If we stopped here then you would get the gradients, but they would move together with the contents of the table view. Luckily table views are UIScrollView child classes and thus you can also implement the UIScrollViewDelegate methods. We are using the one that fires on each movement to adjust the position of the masking layer.</p>

<div class="wp_codebox"><table><tr id="p534733"><td class="code" id="p5347code33"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>scrollViewDidScroll<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIScrollView <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>scrollView
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>CATransaction begin<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>CATransaction setDisableActions<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
    maskLayer.position <span style="color: #002200;">=</span> CGPointMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, scrollView.contentOffset.y<span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>CATransaction commit<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that we also need to disable actions because position is an animatable property on CALayer. If you set that this triggers an implicit animation which would cause the masking layer to lag behind. With actions disabled the layer position is set right away.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-9.48.16-AM.png"><img src="http://www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-9.48.16-AM-161x300.png" alt="" title="Masked Table View" width="161" height="300" class="alignnone size-medium wp-image-5349" /></a></p>
<p>There&#8217;s another problem that only becomes apparent if you start scrolling and the vertical scroll bar shows: it is also affected by the mask which you probably don&#8217;t want because it looks weird. </p>
<p>So instead of actually use the mask for the regular layer masking we add it as a sublayer. Because now the colors are just composited on top of the table view we have to reverse them or else the inside would be whitened out and only the outside would show.</p>

<div class="wp_codebox"><table><tr id="p534734"><td class="code" id="p5347code34"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewWillAppear<span style="color: #002200;">:</span>animated<span style="color: #002200;">&#93;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>maskLayer<span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
        maskLayer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>CAGradientLayer layer<span style="color: #002200;">&#93;</span>;
&nbsp;
        CGColorRef outerColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span> alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>.CGColor;
        CGColorRef innerColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor colorWithWhite<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span> alpha<span style="color: #002200;">:</span><span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#93;</span>.CGColor;
&nbsp;
        maskLayer.colors <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>outerColor, 
                            <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>innerColor, <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>innerColor, <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>outerColor, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
        maskLayer.locations <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObjects<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.0</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.2</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">0.8</span><span style="color: #002200;">&#93;</span>, 
                            <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNumber_Class/"><span style="color: #400080;">NSNumber</span></a> numberWithFloat<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>, <span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
&nbsp;
        maskLayer.bounds <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>,
                            self.tableView.frame.size.width,
                            self.tableView.frame.size.height<span style="color: #002200;">&#41;</span>;
        maskLayer.anchorPoint <span style="color: #002200;">=</span> CGPointZero;
&nbsp;
        <span style="color: #002200;">&#91;</span>self.view.layer addSublayer<span style="color: #002200;">:</span>maskLayer<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This change brought us full circle to essentially adding an imageView on top of the table view to mask out the edge gradients. In this example the rootViewController&#8217;s view is a UITableView and so we have no other place to add this sublayer to. But if the table View were itself a subview of some larger view we could add the gradient layer there and not having to deal with the scrolling.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-10.18.54-AM.png"><img src="http://www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-10.18.54-AM-162x300.png" alt="" title="Tableview with fading not affecting the scroll bar" width="162" height="300" class="alignnone size-medium wp-image-5356" /></a></p>
<p>Actually it&#8217;s not entirely true that there&#8217;s no other layer besides the table view one. You can always move to the view&#8217;s superview and add it there, but this is considered bad form, a view should only fiddle with it&#8217;s own descendants.</p>
<p>This tutorial has shown how you can employ a CAGradientLayer to block out parts of another view. With the same technique you could for example use a CAShapeLayer to mask out an irregular portion of any view. Or you could use a plain image as contents of a plain CALayer for such an effect.</p>
<p>Yet another possibility &#8211; if you want the gradients to be built into the table view itself &#8211; would be to subclass UITableView and do the gradient management there. Either use one large gradient or have two UIViews that draw the gradients individually. There you would put the repositioning of the gradients into the layoutSubviews property instead of the scrollview delegate method.</p>
<p>Happy Masking!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5347&amp;md5=7ab62b433a7edb5a9a9be67b8a589b5a" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/08/adding-fading-gradients-to-uitableview/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5347&amp;md5=7ab62b433a7edb5a9a9be67b8a589b5a" type="text/html" />"
	</item>
		<item>
		<title>Is it safe to install iOS 5 on your everyday iPhone?</title>
		<link>http://www.cocoanetics.com/2011/06/safe-to-install-ios5/</link>
		<comments>http://www.cocoanetics.com/2011/06/safe-to-install-ios5/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 18:14:41 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5168</guid>
		<description><![CDATA[On the heels of the iOS 5 announcement I started getting a multitude of e-mails asking more or less the same thing: I have only my everyday iPhone for developing, so usually I am careful with updating. Do you think that iOS 5 is sufficiently developed and error free to install it on your main phone? Sorry, but actually my first reaction to this question is to laugh out loud. But &#8211; once I have regained my composure &#8211; let me give you a serious answer to this question which is probably really not meant as a joke. Label Buy an ad here Readability I can understand that everybody is excited about the many new features in iOS 5. This includes me, I&#8217;m loving the new Notification Center, I love to play with Safari&#8217;s Reader Mode and Reading List, tweet photos directly from Photo Album and poke around in the settings to see what else is new. Curiosity got the better of me, for a simple reason: I consider it my job to test the new iOS in real life scenarios and so I generally tend to take the plunge. All BETAs go on all my main devices as soon as I can download them. BUT, and that&#8217;s a big but: my business and communications are not solely dependent on my mobile phone. If iOS 5 would have messed up any device of mine, I could still function. The same goes for my MacBook Air which runs the latest preview version of Lion. Again, that&#8217;s mostly out of curiosity and because I consider traveling fun. Serious work is done on my 27&#8243; iMac in my office and there I never would want to take this risk. I found already a handful of glitches that I am going to report bugs to Apple for. Besides of adding a ton of shiny new stuff, Apple has also tweaked many frameworks under the hood. We hear of apps breaking down because in some scenarios a method might not be called that should. There are many other such instances where something broke that we developers are used to relying on. But not all problems are Apple&#8217;s fault. I know one one scenario (in my own code) where a scrollview hack is now cause for a crash. One thing that you could do before iOS 5 is now a cause for an exception, that specifically tells you NOT do do that. It&#8217;s a pity, knowing this &#8220;workaround&#8221; made me feel so smart. But seeing my app crash, makes me feel the opposite: feeling rather dumb. If you update to iOS 5, there is no turning back. There is no way of downgrading back to iOS 4 as far as I understand. Pros tend to buy a so-called &#8220;Sacrificial iPod Touch&#8221; for the express purpose of NOT risking their main hardware. iOS 5 is a loaded gun that not everybody with a developer license should be allowed to handle. Malcom Barclay reported receiving several iTunes reviews mentioning that the users had updated to iOS 5 with the consequence of apps crashing or no longer running. This is funny and sad at the same time. NO, this review was NOT helpful. Generally developers appreciate if you are reporting issues to them, but you should be doing that via a support functionality or e-mail, not via 1-star reviews. In my case I found that Evernote does no longer display note&#8217;s content, both on iPhone and iPad. I can see how this would disable some people who are using Evernote to store every piece of valuable information. In my case I will definitely survive not having it work for some time, it still works on my Macs. You can bet that if thousands of developers install iOS 5 then Apple will be receiving tons of extra bug reports. But this is generally the idea! Apple should be able to trust us developers to treat BETA and preview versions as means to make the final product better, so that the Millions of real-life users have an even better experience when they finally upgrade in the fall. So where does this leave you? Should you or should you not? Nobody can answer this question for you. You SHOULD stick with stable versions if you are dependent on the devices being fully functional. If you are as foolhardy as I am AND you don&#8217;t care if your devices might become unusable for your specific use case, then you CAN try it out. But please PLEASE don&#8217;t bug other developers with the consequences of your decision. And be sure to help Apple out by submitting bug reports for all glitches you find so that the next BETA can be an improvement. Being a member in the developer program is a license &#8230; a [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/06/safe-to-install-ios5/"></g:plusone></div><p>On the heels of the iOS 5 announcement I started getting a multitude of e-mails asking more or less the same thing:</p>
<blockquote><p>I have only my everyday iPhone for developing, so usually I am careful with updating. Do you think that iOS 5 is <em>sufficiently developed</em> and <em>error free</em> to install it on your main phone?</p></blockquote>
<p>Sorry, but actually my first reaction to this question is to laugh out loud. But &#8211; once I have regained my composure &#8211; let me give you a serious answer to this question which is probably really not meant as a joke.</p>
<p><span id="more-5168"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>I can understand that everybody is excited about the many new features in iOS 5. This includes me, I&#8217;m loving the new Notification Center, I love to play with Safari&#8217;s Reader Mode and Reading List, tweet photos directly from Photo Album and poke around in the settings to see what else is new.</p>
<p>Curiosity got the better of me, for a simple reason: I consider it my job to test the new iOS in real life scenarios and so I generally tend to take the plunge. All BETAs go on all my main devices as soon as I can download them. BUT, and that&#8217;s a big but: my business and communications are not solely dependent on my mobile phone. If iOS 5 would have messed up any device of mine, I could still function. The same goes for my MacBook Air which runs the latest preview version of Lion. Again, that&#8217;s mostly out of curiosity and because I consider traveling fun. Serious work is done on my 27&#8243; iMac in my office and there I never would want to take this risk.</p>
<p>I found already a handful of glitches that I am going to report bugs to Apple for. Besides of adding a ton of shiny new stuff, Apple has also tweaked many frameworks under the hood. We hear of apps breaking down because in some scenarios a method might not be called that should. There are many other such instances where something broke that we developers are used to relying on.</p>
<p>But not all problems are Apple&#8217;s fault. I know one one scenario (in my own code) where a scrollview hack is now cause for a crash. One thing that you could do before iOS 5 is now a cause for an exception, that specifically tells you NOT do do that. It&#8217;s a pity, knowing this &#8220;workaround&#8221; made me feel so smart. But seeing my app crash, makes me feel the opposite: feeling rather dumb.</p>
<p>If you update to iOS 5, there is no turning back. There is no way of downgrading back to iOS 4 as far as I understand. Pros tend to buy a so-called &#8220;Sacrificial iPod Touch&#8221; for the express purpose of NOT risking their main hardware.</p>
<p>iOS 5 is a loaded gun that not everybody with a developer license should be allowed to handle. <a href="http://mbarclay.net/?p=1317">Malcom Barclay reported</a> receiving several iTunes reviews mentioning that the users had updated to iOS 5 with the consequence of apps crashing or no longer running. This is funny and sad at the same time.</p>
<p><a href="http://www.cocoanetics.com/files/UK-Train-Times.png"><img class="alignnone size-full wp-image-5169" title="UK-Train-Times" src="http://www.cocoanetics.com/files/UK-Train-Times.png" alt="" width="707" height="114" /></a></p>
<p>NO, this review was NOT helpful. Generally developers appreciate if you are reporting issues to them, but you should be doing that via a support functionality or e-mail, not via 1-star reviews.</p>
<p>In my case I found that Evernote does no longer display note&#8217;s content, both on iPhone and iPad. I can see how this would disable some people who are using Evernote to store every piece of valuable information. In my case I will definitely survive not having it work for some time, it still works on my Macs.</p>
<p>You can bet that if thousands of developers install iOS 5 then Apple will be receiving tons of extra bug reports. But this is generally the idea! Apple should be able to trust us developers to treat BETA and preview versions as means to make the final product better, so that the Millions of real-life users have an even better experience when they finally upgrade in the fall.</p>
<p><em>So where does this leave you? Should you or should you not?</em></p>
<p>Nobody can answer this question for you. You SHOULD stick with stable versions if you are dependent on the devices being fully functional. If you are as foolhardy as I am AND you don&#8217;t care if your devices might become unusable for your specific use case, then you CAN try it out. But please PLEASE don&#8217;t bug other developers with the consequences of your decision. And be sure to help Apple out by submitting bug reports for all glitches you find so that the next BETA can be an improvement.</p>
<p>Being a member in the developer program is a license &#8230; a license to kill &#8230; your device. Your call.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5168&amp;md5=ffc828e7fd3122adae422c55883c7e14" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/06/safe-to-install-ios5/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5168&amp;md5=ffc828e7fd3122adae422c55883c7e14" type="text/html" />"
	</item>
		<item>
		<title>Prepaid 3G Data for Visitors to the USA &#8211; Truth and Fiction</title>
		<link>http://www.cocoanetics.com/2011/05/iphone-3g-data-usa-truth-fiction/</link>
		<comments>http://www.cocoanetics.com/2011/05/iphone-3g-data-usa-truth-fiction/#comments</comments>
		<pubDate>Mon, 30 May 2011 04:42:02 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5121</guid>
		<description><![CDATA[As a fellow iOS Developer you might find yourself in San Francisco for WWDC or maybe on assignment. If you&#8217;re like me then you cannot survive with a modicum of connectivity. Unfortunately AT&#38;T has visitors jump through hoops and has loads of horror stories in stock to deter people from getting what they really want. Thanks to my sponsors at Scribd I&#8217;m here in San Francisco for the second time this year and I would like to summarize what I have learned about your options when it comes to getting affordable wireless data for the short time you&#8217;ll be in the USA. So far I have found two viable options, the easier one being with T-Mobile, the harder but ultimately more enjoyable one going via the main iPhone carrier in the US, AT&#38;T.  Label Buy an ad here Readability T-Mobile T-Mobile is making quite some business it seems as in most locations where you have an AT&#38;T retail store you find a T-Mobile shop quite near, often just across the street. This is the case at the stores that are closest to the Market Street. When I tried the first time, obviously, I wanted to enter the AT&#38;T store first, but they had already closed for the day, T-Mobile has longer hours. At the mentioned location the manager has a professional Sim-Card cutter handy and is only too willing to convert a Web2Go Sim card for the iPhone 4 format. There&#8217;s one caveat: due to T-Mobile using an unusual 3G frequency you won&#8217;t get 3G data with them. You want to get the regular prepaid deal that has access to the unlimited day passes. This is an option that you have to activate every 24 hours, but then you get unlimited EDGE for the duration for a rock bottom rate of $1.49 per day. EDGE is only like slightly more than 100kbps, but that&#8217;s still sufficient to navigate around San Francisco with the maps app, tweet a lot and have your mails pushed to you. Unlimited peace of mind. You quickly get used to going to the special URL (that still works) and activating another 24 hours from your balance. I was told that the balance expires after a certain number of days, but when I returned outside of this period, I still found my balance intact. The only thing that did not work was being redirected to the URL for activating another day pass. But with some friendly in-store help we got this working again, it turns out that with the direct URL I could simply reactivate the service. AT&#38;T If you are a bit more on the adventurous side, then you&#8217;ll get bored with the simplicity of T-Mobile. That&#8217;s where you need to go. If you are a true iPhone fan, then you&#8217;ll also endure the lack of competence on behalf of the AT&#38;T store staff. It actually took me three trips to three stores to get to my final (successful) result. If you just enter a store without some mental preparation (that this blog post aims to provide) then you will hear one or more of the following stories, let me also add where the grain of truth is contained. &#8220;We are not selling Prepaid for Smartphones&#8221; - not true, you are. You&#8217;re just not SUPPORTING it. &#8220;It only works with Android phones&#8221; - there once was a Phone2Go card where this actually was true, but this does no longer apply for the current ones (with orange bubbles design) &#8220;It does not work with iPhones&#8221; - if you don&#8217;t modify the APN settings that might be true. But there are tools to do that which makes it only half-true, namely for n00bs. &#8220;It sucks out all the credit if you use an unsupported phone&#8221; - LOL, the proof for this was one guy that synched his entire mailbox from scratch and found himself out of credit after 100 MB or so. &#8220;We&#8217;re all out of Micro-SIMs in San Francisco&#8221; - that might be true, because the only Micro-SIMs that AT&#38;T stores carry are the packages needed for the iPad and replacements for contract-bound iPhone 4. They are not allowed to sell you a Micro-SIM as prepaid. You basically have two options: 1) to either jump through these hoops with keeping a straight face face while specifically stating that they don&#8217;t have to care what phone you put the card into and that you assume all risk they just should let you have a new prepaid account and sell you a regular SIM card. You will then take care of the necessary modifications yourself. 2) to not go into a corporate AT&#38;T store but to pay a visit to the numerous independent vendors, who are only too happy to help you. Here are the ingredients I used for [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/iphone-3g-data-usa-truth-fiction/"></g:plusone></div><p>As a fellow iOS Developer you might find yourself in San Francisco for WWDC or maybe on assignment. If you&#8217;re like me then you cannot survive with a modicum of connectivity. Unfortunately AT&amp;T has visitors jump through hoops and has loads of horror stories in stock to deter people from getting what they really want.</p>
<p>Thanks to my sponsors at Scribd I&#8217;m here in San Francisco for the second time this year and I would like to summarize what I have learned about your options when it comes to getting affordable wireless data for the short time you&#8217;ll be in the USA.</p>
<p>So far I have found two viable options, the easier one being with T-Mobile, the harder but ultimately more enjoyable one going via the main iPhone carrier in the US, AT&amp;T. <span id="more-5121"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<h3>T-Mobile</h3>
<p>T-Mobile is making quite some business it seems as in most locations where you have an AT&amp;T retail store you find a T-Mobile shop quite near, often just across the street. This is the case at the stores that are closest to the Market Street.</p>
<p>When I tried the first time, obviously, I wanted to enter the AT&amp;T store first, but they had already closed for the day, T-Mobile has longer hours.  At the mentioned location the manager has a professional Sim-Card cutter handy and is only too willing to convert a Web2Go Sim card for the iPhone 4 format. There&#8217;s one caveat: due to T-Mobile using an unusual 3G frequency you won&#8217;t get 3G data with them.</p>
<p>You want to get the regular prepaid deal that has access to the unlimited day passes. This is an option that you have to activate every 24 hours, but then you get unlimited EDGE for the duration for a rock bottom rate of $1.49 per day.  EDGE is only like slightly more than 100kbps, but that&#8217;s still sufficient to navigate around San Francisco with the maps app, tweet a lot and have your mails pushed to you. Unlimited peace of mind.</p>
<p>You quickly get used to going to the special URL (that still works) and activating another 24 hours from your balance. I was told that the balance expires after a certain number of days, but when I returned outside of this period, I still found my balance intact.</p>
<p>The only thing that did not work was being redirected to the URL for activating another day pass. But with some friendly in-store help we got this working again, it turns out that with the direct URL I could simply reactivate the service.</p>
<h3>AT&amp;T</h3>
<p>If you are a bit more on the adventurous side, then you&#8217;ll get bored with the simplicity of T-Mobile. That&#8217;s where you need to go. If you are a true iPhone fan, then you&#8217;ll also endure the lack of competence on behalf of the AT&amp;T store staff. It actually took me three trips to three stores to get to my final (successful) result.</p>
<p>If you just enter a store without some mental preparation (that this blog post aims to provide) then you will hear one or more of the following stories, let me also add where the grain of truth is contained.</p>
<blockquote><p>&#8220;We are not selling Prepaid for Smartphones&#8221;<br />
- not true, you are. You&#8217;re just not SUPPORTING it.</p></blockquote>
<blockquote><p>&#8220;It only works with Android phones&#8221;<br />
- there once was a Phone2Go card where this actually was true, but this does no longer apply for the current ones (with orange bubbles design)</p></blockquote>
<blockquote><p>&#8220;It does not work with iPhones&#8221;<br />
- if you don&#8217;t modify the APN settings that might be true. But there are tools to do that which makes it only half-true, namely for n00bs.</p></blockquote>
<blockquote><p>&#8220;It sucks out all the credit if you use an unsupported phone&#8221;<br />
- LOL, the proof for this was one guy that synched his entire mailbox from scratch and found himself out of credit after 100 MB or so.</p></blockquote>
<blockquote><p>&#8220;We&#8217;re all out of Micro-SIMs in San Francisco&#8221;<br />
- that might be true, because the only Micro-SIMs that AT&amp;T stores carry are the packages needed for the iPad and replacements for contract-bound iPhone 4. They are not allowed to sell you a Micro-SIM as prepaid.</p></blockquote>
<p>You basically have two options: 1) to either jump through these hoops with keeping a straight face face while specifically stating that they don&#8217;t have to care what phone you put the card into and that you assume all risk they just should let you have a new prepaid account and sell you a regular SIM card. You will then take care of the necessary modifications yourself. 2) to not go into a corporate AT&amp;T store but to pay a visit to the numerous independent vendors, who are only too happy to help you.</p>
<p>Here are the ingredients I used for getting AT&amp;T prepaid data on my iPhone 4.</p>
<ol>
<li>iPhone without Sim-Lock, mine is factory-unlocked from the UK</li>
<li>regular size SIM card for GoPhone, make sure that this is one that optionally supports a data package</li>
<li>since I don&#8217;t plan to make any phone calls I chose the 10ct/min Calling Plan</li>
<li>The minimum initial charge is $25, from these the people in the store activated the 100 MB package for $15. You can also do that later, but I found it more convenient to have this done in store already.</li>
<li>iPhone 4 users now have to convert the regular size SIM into a Micro-SIM. This can be done &#8211; if you are brave &#8211; with scissors based on a template, or with a SIM cutter.</li>
<li>The last step is best done if you have an alternate internet connection, like Hotel WiFi. I used the <a href="http://www.unlockit.co.nz">APN Changer</a> online tool to create a profile to set my APN. An alternate route is to do this manually with the official Enterprise Configuration Utility.</li>
<li>That&#8217;s it. I recommend disabling cellular data until you have set everything up, just in case the story about the credits being sucked out is actually true &#8230; <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </li>
</ol>
<p><a href="http://www.cocoanetics.com/files/IMG_06541.png"><img class="alignnone size-full wp-image-5122" title="AT&amp;T APN Settings" src="http://www.cocoanetics.com/files/IMG_06541.png" alt="" width="384" height="576" /></a></p>
<p>If you are in the area new the Moscone center, locals call it &#8220;Market Street&#8221;, then tweet up <a href="http://twitter.com/jsjohnst">Jeremy Johnstone</a> who lives a block from there and would love to show off his mad SIM cutting skills with a professional tool. I have a feeling that he&#8217;ll never run out of sponsored beers for the next weeks. <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>And if you are in the Fisherman&#8217;s Wharf area, you can have the full service option from Fernando Cortes who runs a small phone shop (AT&amp;T Affiliate) on <a href="http://maps.google.com/maps/place?ftid=0x808580d724a7fd93:0x3e52bafb9ac02528&amp;q=2056+Chestnut+Street&amp;hl=en&amp;sll=37.800755,-122.437567&amp;sspn=0.006295,0.006295&amp;ie=UTF8&amp;ll=37.804461,-122.446039&amp;spn=0,0&amp;z=16">2056 Chestnut Street</a>. It&#8217;s a bit out of the way but he&#8217;s open on weekends too, so I can definitely recommend that you go the distance if you don&#8217;t want to hear silly stories and combine the procurement of 3G data with a visit to the Wharf.</p>
<p>There might be one other option: some people have gotten replacement iPhone 4 SIMs claiming that theirs was broken. But I prefer to stick to the truth, it shall set you free.</p>
<p>One more note: Your prepaid balance expires if you don&#8217;t refill periodically. The expiration durations are 30 days for less than $25, $25 through $75 expire in 90 days and $100 refill expires in 365 days. So if you know that you&#8217;d like to come back to next year&#8217;s WWDC, then you&#8217;ll either have to start the dance from scratch or keep your account alive by adding credit to it every couple of months. I&#8217;m thinking about topping it off for $100 once before I leave and then be done with it.</p>
<p><strong>Update June 4th, a week later: </strong>Now my first 100 MB were used up, so I refilled my account via credit card for $100 (to get the 365 days non-expiration) and from these I used $25 for 500 MB MB. That should be more than enough to get me over WWDC and the navigating/twittering for my second week in San Francisco.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5121&amp;md5=5f1a3884d24b78d876b378eec9c802ea" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/05/iphone-3g-data-usa-truth-fiction/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5121&amp;md5=5f1a3884d24b78d876b378eec9c802ea" type="text/html" />"
	</item>
		<item>
		<title>Tons of Changes</title>
		<link>http://www.cocoanetics.com/2011/05/tons-of-changes/</link>
		<comments>http://www.cocoanetics.com/2011/05/tons-of-changes/#comments</comments>
		<pubDate>Fri, 27 May 2011 08:05:18 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5112</guid>
		<description><![CDATA[Devin Snipes asks: I&#8217;ve advanced in my iOS development and have officially started work on a client project. My client has requested tons of changes since I told them the application was complete. Should I keep doing these changes or just stop. I under-charged them, made several thousand changes and also felt like I over-worked myself. How would you deal with this? My second question is related to the somewhat &#8216;legal&#8217; matters of iOS development. Do you have a standard iOS development contract that you request your clients to abide by? If so, could you send me a copy or could I look over it to get some idea as to what I should do. Both are really good questions. (&#8220;Good question&#8221; usually means that they don&#8217;t have a simple answer)But let me attempt to go back in my own experience and give you a couple of pointers as to how I dealt with exactly the same situation and what I learned from it. Label Buy an ad here Readability As a rule of thumb people who contract you for making an app are cheap. Cheap as in Uncle Scrooge. And they know that whoever commits to a number first, loses. That&#8217;s why they ask you for a quote knowing dead well that as a beginning programmer you are absolutely incapable of judging the true amount of work that you will put into the app. Being the kind of lottery that is the app store, these couple of hundred dollars are sort of the price for their ticket. Low cost, potentially big rewards. Buy another name this is called &#8220;business sense&#8221;. Keep costs low to have a big margin. So they say &#8220;it&#8217;s a really simple idea, it just needs this, this and this. How soon can you have done it, for what price?&#8221; And that&#8217;s a trick question that tricks beginning developers into thinking about facts. You think &#8220;ok, these are 3 fairly simple items, maybe I can do these in x hours&#8221;, you multiply this by a rate that you feel you should be worth and that&#8217;s what you quote. Only to find that when you present the first version to the client you get a &#8220;And what about feature x? I thought it is obvious that this has to be in there as well! Without that the app is worthless&#8221;. And this goes several times back and forth until you have spend three times as much on the job as you quoted initially. Then there&#8217;s work that you did not quote, but still need to do, because the client has no Apple account, you need to build, hand-hold the client through the submission process and the app starts getting downloads you get the crash reports. The app might be successful like in the case of my first contracting client who made $10,000 in the first month, with an app that I charged him $400 for. Or the app might crash and burn and you hear &#8220;I would have paid you more, but unfortunately the app is not selling&#8221;. The theme of all this being: you have lots of work, but don&#8217;t get paid for it. On a tangent you might be wisening up and refuse to work any more, only to find an e-mail from your client requesting that you hand over the source code so that another developer will continue on the app. I know this from having fallen prey to several such sharks myself. So how can you avoid being tricked like that? Developing iOS apps should be rewarding, not draining you. Your second question goes in the right direction, but let me tell you outright that I don&#8217;t have a standard iOS development contract. You might find some on the Internet, but I fear that you suspect that if you had a written contract that this would be the magic bullet that would make it all alright for you. But it doesn&#8217;t. No contract is worth the paper it is printed on, if you don&#8217;t know what it is supposed to do. A contract is nothing but a summary of items that two parties are agreeing upon. So make up your own! You are fully capable of writing on a piece of paper &#8220;Devin Snipes and Client X are agreeing that &#8230;&#8221; and fill in what you feel is worth agreeing on. Let me give you a list of items that I would put in there personally: Design I tell people: &#8221; I am not a designer, I am a programmer&#8221;. I expect UI/UX design to be provided in form of Mockups and written functional specification. That means I want a document that describes what the app can do and essentially how you navigate between it&#8217;s functions. My strength is writing efficient code fast, it would [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/tons-of-changes/"></g:plusone></div><p><a href="http://www.cocoapedia.org/wiki/Devin_Snipes">Devin Snipes</a> asks:</p>
<blockquote><p>I&#8217;ve advanced in my iOS development and have officially started work on a client project. My client has requested tons of changes since I told them the application was complete. Should I keep doing these changes or just stop. I under-charged them, made several thousand changes and also felt like I over-worked myself. How would you deal with this?</p>
<p>My second question is related to the somewhat &#8216;legal&#8217; matters of iOS development. Do you have a standard iOS development contract that you request your clients to abide by? If so, could you send me a copy or could I look over it to get some idea as to what I should do.</p></blockquote>
<p>Both are really good questions. (&#8220;Good question&#8221; usually means that they don&#8217;t have a simple answer)But let me attempt to go back in my own experience and give you a couple of pointers as to how I dealt with exactly the same situation and what I learned from it.</p>
<p><span id="more-5112"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>As a rule of thumb people who contract you for making an app are cheap. Cheap as in Uncle Scrooge. And they know that whoever commits to a number first, loses. That&#8217;s why they ask you for a quote knowing dead well that as a beginning programmer you are absolutely incapable of judging the true amount of work that you will put into the app. Being the kind of lottery that is the app store, these couple of hundred dollars are sort of the price for their ticket. Low cost, potentially big rewards. Buy another name this is called &#8220;business sense&#8221;. Keep costs low to have a big margin.</p>
<p>So they say &#8220;it&#8217;s a really simple idea, it just needs this, this and this. How soon can you have done it, for what price?&#8221; And that&#8217;s a trick question that tricks beginning developers into thinking about facts. You think &#8220;ok, these are 3 fairly simple items, maybe I can do these in x hours&#8221;, you multiply this by a rate that you feel you should be worth and that&#8217;s what you quote. Only to find that when you present the first version to the client you get a &#8220;And what about feature x? I thought it is obvious that this has to be in there as well! Without that the app is worthless&#8221;. And this goes several times back and forth until you have spend three times as much on the job as you quoted initially.</p>
<p>Then there&#8217;s work that you did not quote, but still need to do, because the client has no Apple account, you need to build, hand-hold the client through the submission process and the app starts getting downloads you get the crash reports. The app might be successful like in the case of my first contracting client who made $10,000 in the first month, with an app that I charged him $400 for. Or the app might crash and burn and you hear &#8220;I would have paid you more, but unfortunately the app is not selling&#8221;.</p>
<p>The theme of all this being: you have lots of work, but don&#8217;t get paid for it. On a tangent you might be wisening up and refuse to work any more, only to find an e-mail from your client requesting that you hand over the source code so that another developer will continue on the app.</p>
<p>I know this from having fallen prey to several such sharks myself. So how can you avoid being tricked like that? Developing iOS apps should be rewarding, not draining you.</p>
<p>Your second question goes in the right direction, but let me tell you outright that I don&#8217;t have a standard iOS development contract. You might find some on the Internet, but I fear that you suspect that if you had a written contract that this would be the magic bullet that would make it all alright for you. But it doesn&#8217;t. No contract is worth the paper it is printed on, if you don&#8217;t know what it is supposed to do. A contract is nothing but a summary of items that two parties are agreeing upon. So make up your own! You are fully capable of writing on a piece of paper &#8220;Devin Snipes and Client X are agreeing that &#8230;&#8221; and fill in what you feel is worth agreeing on.</p>
<p>Let me give you a list of items that I would put in there personally:</p>
<h1>Design</h1>
<p>I tell people: &#8221; I am not a designer, I am a programmer&#8221;. I expect UI/UX design to be provided in form of Mockups and written functional specification. That means I want a document that describes what the app can do and essentially how you navigate between it&#8217;s functions. My strength is writing efficient code fast, it would be a waste of the client&#8217;s money if he also paid me for photoshopping some Google Images into app icons.</p>
<p>If you are dealing with companies then most of the time they have their own designers, you can offer to do a (chargeable) workshop with them to give them some pointers as to how to approach the UX/UI and technical stuff like what resolution images you want and that the double-resolution images should be named a certain way.</p>
<p>If the client cannot provide that, then I have friends and partners <a title="Design by a Friend" href="http://www.cocoanetics.com/2011/05/design-by-a-friend/">who can help</a> him distill out such a spec, for a price. In either case you should only start touching code once you feel that all questions are answered and all functions are set. Unless the client wants a prototype, which is a project of its own.</p>
<p>Tell your client &#8220;Apple says a good app is 60% design&#8221;. This means that they can save 60% of the total app costs of they do all the design legwork before talking to you. You know, a typical designer charges around $500 for an app icon. Not because it&#8217;s the first piece of artwork that&#8217;s seen from an app. The reason for this high cost is that even a pro would work 1-2 days on it. Knowing this, how do you now feel that you promised that you would do this &#8220;quick app&#8221; in a week for the same amount that somebody else pays a designer for just the icon?</p>
<h1>Price</h1>
<p>If you have the strength then you should not commit to a quote. Ideally you will charge for each and every hour you spend on this project and &#8211; trust me &#8211; you have NO IDEA how many hours this will actually be. But if they insist and threaten to take the business else where (and you need the money) then you can put together a quote, but itemize it. Referring to the earlier mentioned design document you should make a list, item 1 &#8230;. x hours, item 2 &#8230;. y hours, etc.</p>
<p>Don&#8217;t forget to allot time for: project setup, communication, app store submission, version 1 bug fixing, testing and whatever work you have to do besides of coding. And when you have estimated all the hours, take everything times two. You will arrive at a final quote that is orders of magnitude higher than what you would have quoted shooting from the hip.</p>
<p>And then when the client complains that he thinks you are calculating too many hours for &#8220;such a simple app&#8221;, you tell him: for an all in quote you have to factor in unforeseen eventualities, that&#8217;s why he probably will be way better of just paying your billable hours every 2 weeks or monthly. An hour-based arrangement should always feel to the client as being the better deal, because he knows that for all-in projects you are probably faster than you estimate.</p>
<p>Honestly I have the most respect for iOS developers who have an hour-based ongoing arrangement with their clients. And I kind of feel sad for the poor solo developers who let themselves be suckered into too-cheap all-in deals.</p>
<p>There is another philosophy, but this applies more for small contracting outfits: agile project management, called SCRUM. There the amount of effort for certain features is not estimated in hours, but relative to each other as a number of points. One item (called a &#8220;User Story&#8221;) could have 5 points and if something else is the same amount of work, it will have the same number of points. With scrum the customer will never see hours, but you will have a certain mutliplier (that only you know) to convert these so called &#8220;Story Points&#8221; into currency.</p>
<h1>Scope</h1>
<p>On several occasions you should stress that the agreed upon project scope is only what is written down in the functional spec design document. There are absolutely NO &#8220;obvious features&#8221; and there is no &#8220;I thought we also said we would do x&#8221;. If it&#8217;s not in the spec then it&#8217;s not covered. The client CAN have it, but it increases the project cost.</p>
<p>It is usually sufficient to just make a quote addendum similar to the first itemized quote: new item A &#8230;. x hours. And then ask the client to agree to the project extension in an e-mail. Everything that makes the project bigger you want to have documented somewhere. You could add it to the functional specification document or simply collect it in your mail box. But you might need to go back eventually and present to your client &#8211; refusing to pay more &#8211; the items that he sent you his approval for.</p>
<p>I told you earlier: a contract is everything that two people agree upon verbally or in written words. So those e-mails are essentially mini-contracts themselves. But don&#8217;t make the mistake of only discussing this on the phone, because people will generally choose to only remember talking that suits their agenda. On a study that was done, they found that people lie the most on the telephone because there is no record of it.</p>
<p>As a beginner you might be falling in love with all the nifty little things you could add to an app to make it &#8220;better&#8221;. The client didn&#8217;t ask for it, but hey, why not do a UIView animation from a to b. It looks SO MUCH MORE professional with that &#8230; STOP THAT right now! If you have cool ideas, don&#8217;t just put them in the app, but instead suggest them to the client. Most likely he will value your initiative but you will then actually have his approval for the extra stuff.</p>
<p>It is your job to follow the spec as closely as you can with the least amount of extra work. I like to structure my code to be reusing components wherever I can. So if you think that something you develop for one client might be useful later on, then design for reusablilty. This means for example, writing a delegate protocol instead of having all parameters of a class in fixed instance variables. This is not much extra work, but might save you some in the future. But bear in mind that you are not getting paid for too much creative programming. You should not expect your client to be happy about paying for your future benefits.</p>
<p>You want to write the least amount of code that covers the requirements. And if time permits make it loosely coupled and written in a way that you can come back to this code in half a year and still know how the pieces fit together.</p>
<h1>Scheduling</h1>
<p>Be clear about the amount of time you can put into a client&#8217;s project. Often a client would expect you to finish the project in the same amount that a full-time developer would take. But especially when you&#8217;re still going to school or university you might not have more than a couple of hours every day to work on this.  Even full time I am not estimated with more than 6 useful coding hours per day. Maybe I&#8217;m getting old (37 years) but writing good code is hard work on my brain.</p>
<p>Your client probably approached you, Devin, not because of your speed, but because he knows that he will get his app made for cheap. So right after nailing you on a low price he will try to get you committed on a release date. <strong>Rule Number 1 in IT: It&#8217;s finished, when it&#8217;s done.</strong></p>
<p>Just be honest with the guy. You&#8217;ll do your best to do some magic, but miracles take a little longer. If he needs it by a certain date then you need to get more resources. If you estimate 40 hours for an app, then 2 guys might be able to do it in about half the time, possibly slightly more because of the additional overhead. You have to judge when to sub-contract parts of the app to another developer. Don&#8217;t feel bad if you have to do, your thoughts should not be revolving around how much money you will lose because it now goes to the second developer. If you were smart in your negotiations then you have enough room to keep 10-20% of the payment and still pass on a decent amount per hour to your samaritan.</p>
<h1>Ownership</h1>
<p>Generally if there is no other agreement made then the (self-employed) developer retains ownership of the source code. It&#8217;s just like any other written piece of art. He who wrote it owns the authorship rights. The client only implicitly gets the right to commercial use of the final product he commissioned. Without a contract that modifies this default situation you own the source and don&#8217;t have to give it to anybody. BTW this is not true for employees, there everything they invent belongs to their employer per default.</p>
<p>This is important to know for two reasons: 1) if a client is smart and has you sign a contract containing the &#8220;hand-me-over-the-source-clause&#8221; then you will need to be aware of this as this means you potentially lose any future business with him. Thus you have to charge more up front. 2) if there is a conflict of interest or he does not pay you have a great hostage.</p>
<p>I usually keep all project source code in a repository on my server so that I have at least two copies, one on my local machine (plus Timemachine backup), one on my server on the internet. For very select clients I give them a read-only access to the repository, but only if I am certain that we have an ongoing business relationship. There is the rare case when I am handing over the source, but that&#8217;s usually when I feel that there&#8217;s no hope of every making another Dime from this guy.</p>
<p>But even handing over the code does not mean you cannot reuse parts of what you made. When you code you learn how to achieve certain things better and faster and this knowledge you cannot selectively forget. Who is to keep you from building a new class from scratch that does exactly work the same as the other class the source of which you just handed over? (Well, in the US your client theoretically has the option of patenting what you made, but let&#8217;s not worry about this for now)</p>
<h1>Conflict Resolution</h1>
<p>There are two ways how people get paid for projects: either by sending invoices periodically for the hours they worked, or by sending two or three invoices for installments of the total project cost. You could agree on a third up front on signing, a third when the first prototype is done and a third the day you submit to the app store. Any such payment can also be seen as the client being ok with what happened so far.</p>
<p>If you had any form of contract or agreement then the payment schedule would have been a part of it. But then you would also have an agreement on the other items mentioned above. So what do you do &#8211; as a beginner &#8211; if the client tells you that he won&#8217;t pay anything more than he original was quoted. I had this very situation about a year ago, have a look at the recommendations of <a title="How to deal with contracting customers who won't pay" href="http://www.cocoanetics.com/2010/02/how-to-deal-with-contracting-customers-who-wont-pay/">how to deal with contracting clients who don&#8217;t want to pay</a>.</p>
<p>Now about your case: I definitely recommend you compile a list of the original specs and then a second list with all the items that were added later. The original specs are what payment was agreed on. The additional specs still need such an agreement. In one case the original project quote was for 400 Euros and by making this addendum list I was able to show to the client that he approved over 100% more hours of work. Multiplied with my rate at that time, that increased the project payment to 1500 Euros. There were some items where I couldn&#8217;t find any e-mail with him responding OK, so these I essentially did for free.</p>
<p>If your client is unfazed by the second list, then you should be clear about being willing to walk away from the project. Either you agree to agree on a mode that you both can live with. Or you agree to disagree. The client is free to find himself another developer (whom you should secretly warn about him and send him to this article). Your stance should communicate that you are definitely willing to drop everything related to his app if no agreement can be reached.</p>
<p>As a beginner your feeling might be &#8220;oh my god this is my only customer and if he doesn&#8217;t like me I might never again find another&#8221;. But don&#8217;t you worry, there is much more iOS work to be done than there are developers. Usually demonstrating this &#8220;willingness to walk away&#8221; does NOT result in terminating the project. Rather the client will start to take you seriously and stop seeing you as a cheap coding monkey but as a human being who stands up for himself. And probably willing to negotiate agreeable terms as he still wants this app to be finished and put on the app store.</p>
<p>And you know, an unhappy programmer might be forgetting a crashing bug in the app, but not be around to quickly fix it. So it&#8217;s also in the client&#8217;s best interest to keep you happy.</p>
<h1>Bugs, New Features</h1>
<p>Software is never really &#8220;done&#8221;. After submission to the App Store your client might contact you because of some crash reports or customer feedback. Typically the app should have been tested thoroughly and bugs should not happen, right? But they do, if only for obscure scenarios where you used a 4.x feature and the app is running on a 3.x iPhone. Stuff that&#8217;s obvious to you in hindsight.</p>
<p>Now is the second time to agree on an hourly rate for quick fixes and one or the other enhancement. Again, if the user insists on quotes then give him a high quote for a &#8220;maintenance contract&#8221;, payable monthly. You are a professional and you are not dragging your feet when fixing your bugs. Hey, it&#8217;s a matter of pride. If the client wants to again nail you on a fixed quote, then that means you have not learned your lesson and he still does not take you seriously.</p>
<p>You want to have a situation of trust: he should trust you to work as fast and efficient as you possibly can providing quality that matches the agreed specifications. You should be able to trust that he will pay and treat you as a professional developer.</p>
<h1>Conclusion</h1>
<p>You might have grown to be a great iOS developer, but now you need to also train your business sense. These guidelines and insights should give you a nudge in the right direction. Your situation happens to every fledgling contractor. In the worst case you should change clients. In the best case you can talk with your client and find common ground based in reciprocal trust and respect.</p>
<p>Granted, beggars can&#8217;t be choosers. You might be saying &#8220;I was young, I needed the money&#8221;. But does that mean you have to do the equivalent of slave labor? Yes, you can have low rates at the beginning, but you still should adhere to some common sense guidelines as they are contained in this article. As you get better, you would not change your approach, but raise your hourly rates.</p>
<p>Most people have no idea how much work it is that has to go into a respectable app. They are not stupid, or maliciously ignorant. It will be your job to dissuade a couple of people from making &#8220;a quick app&#8221; and be picky about your contracts to take on the projects that are intellectually challenging and where you can work with nice and smart people at eye-level.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5112&amp;md5=4ec4642ce20aa255b7fda6deb47181ee" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/05/tons-of-changes/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5112&amp;md5=4ec4642ce20aa255b7fda6deb47181ee" type="text/html" />"
	</item>
		<item>
		<title>What Impact will new Web-Technologies have on iOS Developers?</title>
		<link>http://www.cocoanetics.com/2011/05/what-impact-will-new-web-technologies-have-on-ios-developers/</link>
		<comments>http://www.cocoanetics.com/2011/05/what-impact-will-new-web-technologies-have-on-ios-developers/#comments</comments>
		<pubDate>Wed, 25 May 2011 10:23:03 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5082</guid>
		<description><![CDATA[Jamar Parris asks: I&#8217;ve really been contemplating whether to focus my efforts on one versus the other as I&#8217;m still new to both technologies. What impact do you think will HTML5, CSS3, WebGL, etc have on Objective-C iOS developers? The question web versus native is one that makes waves every once in a while when there is support for a new formerly native technology in browsers or when Apple rejects an app. Let me expand my answer a bit, as there were a couple of recent experiences that serve well to underline my opinion on this question. Label Buy an ad here Readability When I went full steam ahead with being a full-time iOS developer I made the conscious decision to only focus on a single platform. The main reason for doing so is that I feel that only when focussing like this you have a chance to become great at it. As a general rule of thumb you need to spend about 10,000 hours on any subject matter to be world class. Be it art or science, you need to put in the hours to grow the skills you need to excel at the topic you have chosen. Of course you can be a Jack of all Trades, but those typically never make much money. There are two career paths that are possible in IT: you can either strive to become an expert at programming, some large corporations call these &#8220;programmer/analyst&#8221;. Or you can develop into a management role. It is only on rare occasions that you will find great managers that are also great and active developers. Pure development (i.e. coding) is only a part of what does into making an app. Lots of it is overhead that good management tries to keep from hindering the developers. Having said that you can look into becoming a manager/leader even without committing to a single platform. As a manager your platform is people and the OS of these &#8211; if you will &#8211; are their needs, wishes and social interactions between them. Now, that&#8217;s more like a comment on the &#8220;focussing my efforts&#8221; part of your question. Yes, I think you should definitely focus. But first the question is Management versus Expert path. Now for the expert path, there is only one answer that I can give you and that is from my own autobiography. I am putting all my eggs in the &#8220;native&#8221; basket. Off the top of my head, here are my primary reasons: I love Cocoa and Objective-C for their elegance and power There are orders of magnitude more web developers on Earth than iOS developers, so it is rather more likely that I can be at the top in iOS than in web tech. Experts generally earn more than Generalists and iOS Experts are currently the most sought after bunch. I have yet to see a business model on the web that would work for solo-developers like myself. I can make and sell apps at virtually no cost. For monetization on the web you only have SOAS (Software as a Service) and Ads, both of which are only feasable if you build a business around them, not for doing an app here or there. I love Apple and by working within their eco system I cast my vote for their awesomeness I hate JavaScript, frown at Java and .NET and actively dislike Microsoft. Granted, those are mostly emotional reasons, but I think all reasons you can have are such. It boils down to my core belief that I think that native development is more fun and has better rewards than web tech. Let me also properly answer the second part, which is not really asking about my opinion what is better. Sorry for going overboard here. The second question is actually about what I think the impact will be. And there I can give you a less emotional answer, again from my perspective. With more and more apps pushing onto the stage that is the app store Apple has set forth some guidelines for app reviewers that we can also consider when making design decisions, long before touching any code on any platform. The clear message is: we want no more fart apps and an app should be way more than a web page to be approved. Apps that would look the same if you did them in HTML/CSS face a high likelihood of being rejected these days. The example I can quote is this: iCatalog. This is a white label app I own and that my partner ICS in the USA is selling as a catalog on iPad solution to their clients. With some smart technology we take the PDFs and make them interactive. Now there are some customers who are able to provide full [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/what-impact-will-new-web-technologies-have-on-ios-developers/"></g:plusone></div><p>Jamar Parris asks:</p>
<blockquote><p>I&#8217;ve really been contemplating whether to focus my efforts on one versus the other as I&#8217;m still new to both technologies. What impact do you think will HTML5, CSS3, WebGL, etc have on Objective-C iOS developers?</p></blockquote>
<p>The question web versus native is one that makes waves every once in a while when there is support for a new formerly native technology in browsers or when Apple rejects an app. Let me expand my answer a bit, as there were a couple of recent experiences that serve well to underline my opinion on this question.</p>
<p><span id="more-5082"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>When I went full steam ahead with being a full-time iOS developer I made the conscious decision to only focus on a single platform. The main reason for doing so is that I feel that only when focussing like this you have a chance to become great at it. As a general rule of thumb you need to spend about 10,000 hours on any subject matter to be world class. Be it art or science, you need to put in the hours to grow the skills you need to excel at the topic you have chosen.</p>
<p>Of course you can be a Jack of all Trades, but those typically never make much money. There are two career paths that are possible in IT: you can either strive to become an expert at programming, some large corporations call these &#8220;programmer/analyst&#8221;. Or you can develop into a management role. It is only on rare occasions that you will find great managers that are also great and active developers. Pure development (i.e. coding) is only a part of what does into making an app. Lots of it is overhead that good management tries to keep from hindering the developers.</p>
<p>Having said that you can look into becoming a manager/leader even without committing to a single platform. As a manager your platform is people and the OS of these &#8211; if you will &#8211; are their needs, wishes and social interactions between them.</p>
<p>Now, that&#8217;s more like a comment on the &#8220;focussing my efforts&#8221; part of your question. Yes, I think you should definitely focus. But first the question is Management versus Expert path.</p>
<p>Now for the expert path, there is only one answer that I can give you and that is from my own autobiography. I am putting all my eggs in the &#8220;native&#8221; basket. Off the top of my head, here are my primary reasons:</p>
<ul>
<li>I love Cocoa and Objective-C for their elegance and power</li>
<li>There are orders of magnitude more web developers on Earth than iOS developers, so it is rather more likely that I can be at the top in iOS than in web tech.</li>
<li>Experts generally earn more than Generalists and iOS Experts are currently the most sought after bunch.</li>
<li>I have yet to see a business model on the web that would work for solo-developers like myself. I can make and sell apps at virtually no cost. For monetization on the web you only have SOAS (Software as a Service) and Ads, both of which are only feasable if you build a business around them, not for doing an app here or there.</li>
<li>I love Apple and by working within their eco system I cast my vote for their awesomeness</li>
<li>I hate JavaScript, frown at Java and .NET and actively dislike Microsoft.</li>
</ul>
<p>Granted, those are mostly emotional reasons, but I think all reasons you can have are such. It boils down to my core belief that I think that native development is more fun and has better rewards than web tech.</p>
<p>Let me also properly answer the second part, which is not really asking about my opinion what is better. Sorry for going overboard here. The second question is actually about what I think the impact will be. And there I can give you a less emotional answer, again from my perspective.</p>
<p>With more and more apps pushing onto the stage that is the app store Apple has set forth some guidelines for app reviewers that we can also consider when making design decisions, long before touching any code on any platform. The clear message is: we want no more fart apps and an app should be way more than a web page to be approved. Apps that would look the same if you did them in HTML/CSS face a high likelihood of being rejected these days.</p>
<p>The example I can quote is this: iCatalog. This is a white label app I own and that my partner ICS in the USA is selling as a catalog on iPad solution to their clients. With some smart technology we take the PDFs and make them interactive. Now there are some customers who are able to provide full lists of products in XML, for these we can do a nice solution where you can select size and color options and get price information. For other clients we only have product names and URLs. There we would display a webview with the product page in it. With the problem that these would obviously only work if you are connected to the internet.</p>
<p>One of these web-catalogs recently got rejected by Apple, citing:</p>
<blockquote><p>We&#8217;ve completed the review of your app, but cannot post this version to the App Store because it did not comply with the App Store Review Guidelines, as detailed below:</p>
<ul>
<li>12.3: Apps that are simply web clippings, content aggregators, or a collection of links, may be rejected</li>
</ul>
</blockquote>
<p>For me as a developer it is hard to get such a rejection. Fortunately we were able to argue the plethora of additional native features that iCatalog boasts in our favor. Also we just had completed a new offline feature that went into the app to sweeten the deal for Apple. So it went through and got approved on the second go.</p>
<p>What does this tell us? For one thing, Apple is tightening the noose around apps that are bordering on being repackaged web apps. So if you start making an app, make sure that you use native device features (like, sensors, CoreAnimation, location, camera, etc) that make clear the value proposition of your work.</p>
<p>If something works just as well as a web app, then by all means have it as web app! Most of the time these would be free services that just have a viewing component for which you need Internet anyway. In some rare examples like Readability the problem there was a disagreement over sharing 30% of subscription revenues with Apple that prompted them to go the web-based route.</p>
<p>New HTML technologies make inroads into former native app territories. Like you can get position data now in mobile browsers. So the number of reasons for doing native apps might be seen decreasing over time. Apple&#8217;s Nitro JavaScript engine is only present in mobile Safari for the very same reason: they don&#8217;t want developers to do fancy JS tricks in UIWebViews like so many are doing it these days to get rich text editing or HTML rendering. Apple established a developer program of its own right on the developer center, on par with the iOS and Mac ones. This also hints at what they are trying to achieve.</p>
<p>Apple wants native apps to make use of all what their devices are offering. Apple wants web apps to work and platform-independent as possible. And you know, WebKit is Open Source and the de facto standard for rendering web pages.</p>
<p>On the other side, while technologies like WebGL are nice in theory, native platforms will always stay ahead in performance due to the native interfaces available to talk more or less directly with the GPU and hardware. We have seen several apps recently that are showing off some really cool ideas of what you can do with this power, like the one that tracks your face to adjust a 3D rendering.</p>
<p>If you are interested in local mobile computing power and the interesting things that you can do with shaky or no internet connection then native is the way to go. If you can outsource the computing power to the cloud and internet connection is satisfactorily then you can also be web-based. But frankly the first option gets me way more excited. Even though there is a promise of an always available internet connection, the reality proves that internet has varying degrees of connectivity. While you might be ok in big cities, everybody knows a great deal of places that continue to have spotty or no service at all.</p>
<p>While many internet-based startups blissfully ignore this fact when building their service, this is a reality where web apps don&#8217;t have a good answer for. Native apps can detect what level of connectivity exists and dynamically modify their behavior. Like being able to fully play a game on an airplane and upload your achievements later when you are back online. Web apps try to solve the connection problem in two ways: by keeping session state on the server and identifying your session by cookie or URL. Or by the new HTML offline features. This might be a solution for some light-weight scenarios, but I don&#8217;t lots of iPhone users installing HTML web apps on their springboards. It just feels weird to me.</p>
<p>But I may be surprised if somebody comes up with some new and innovative use for all the new web technologies. But so far I have not seen a single web app that I would prefer over a native app on my Mac or iPhone. I have the distinct feeling that too much brainpower is used on web platforms to work around inherent limitations. The same brainpower is put to better use on an established native platform which gives you GPU-accelerated UI paradigms, multi-touch handling and other hardware features neatly packaged in APIs that &#8211; for the most part &#8211; are a pleasure to work with.</p>
<p>There one other trap in treating this as a either/or question. The mobile market as a wholes is growing exponentially. So it does not mean that moving from the native to the web or vice versa takes something away from either platform. For each such decision there are dozens of competitors only to willing to step into the supposed hole you left. So on the grand scale it does not matter what you as a single person decide to go into. If you don&#8217;t become the next shooting star iOS developer, then somebody else will.</p>
<p>To summarize I would say, you should go for the platform or role that inspires you the most. For me it is Apple, native and cool uses of the hardware.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5082&amp;md5=67af50571a69046fc700af32e5573324" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/05/what-impact-will-new-web-technologies-have-on-ios-developers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5082&amp;md5=67af50571a69046fc700af32e5573324" type="text/html" />"
	</item>
		<item>
		<title>To Universal or Not</title>
		<link>http://www.cocoanetics.com/2011/05/to-universal-or-not/</link>
		<comments>http://www.cocoanetics.com/2011/05/to-universal-or-not/#comments</comments>
		<pubDate>Wed, 18 May 2011 13:06:31 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5046</guid>
		<description><![CDATA[Daniel Wood asked: Considering making a Blockees universal. What are people&#8217;s thoughts on universal apps? Good for users, but splits sales between devices. My first gut response was, that IMHO users love universal apps, whereas marketeers and financiers hate them. HD or &#8220;for iPad&#8221; versions can generally be sold for a higher price. Daniel then voiced his fear that if you have an universal app you might &#8220;dilute&#8221; your download rank on iTunes. Again I responded from my feeling that I don&#8217;t think that this is right. Daniel challenged me to prove it. And so I will. Label Buy an ad here Readability I went to Applyzer and copy/pasted the top 100 free US apps from category &#8220;top overall&#8221; from iPhone and iPad into a graphic. Applyzer has the top 1000 for for the following categories: Paid (iPhone/iPod) Free (iPhone/iPod) Grossing (iPhone/iPod) Paid (iPad) Free (iPad) Grossing (iPad) Paid (Mac) Free (Mac) Grossing (Mac) Then I went through the list and marked all apps that are showing as universal in iTunes. Then I searched where the same app would be in both ranks. Finally I made a quick survey if I could spot apps that had a separate iPhone and iPad version. Note that this was done from hand and I might have missed a couple of connections. But even then I think the picture is rather obvious. There were 27 universal apps in the free overall US top 100 and 33 in the iPad chart. Of these I could find 16 universal apps that where ranking similarily high in both charts. 11 universal iPhone apps did not show in the top 100 iPad chart. 14 universal iPad apps did not show in the top 100 iPhone/iPod chart. Possibly they were only slightly outside the top 100, I did not check. The percentage of successful universal apps is an order of magnitude higher than dedicated versions. Amongst the top 100 (again only quickly looking visually) I could only find 4 apps that both had separate versions. I invite your scrutiny of this casual analysis of mine, however I think that this graphic can only lead to this answer to Daniel&#8217;s question: Make your free app universal, if you are NOT Rovio. I think this analysis debunks the myth that making a free app universal is bad for it&#8217;s ranking. &#160;]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/05/to-universal-or-not/"></g:plusone></div><p><a href="http://www.cocoapedia.org/wiki/Daniel_Wood">Daniel Wood</a> asked:</p>
<blockquote><p>Considering making a Blockees universal. What are people&#8217;s thoughts on universal apps? Good for users, but splits sales between devices.</p></blockquote>
<p>My first gut response was, that IMHO users love universal apps, whereas marketeers and financiers hate them. HD or &#8220;for iPad&#8221; versions can generally be sold for a higher price.</p>
<p>Daniel then voiced his fear that if you have an universal app you might &#8220;dilute&#8221; your download rank on iTunes. Again I responded from my feeling that I don&#8217;t think that this is right. Daniel challenged me to prove it. And so I will.</p>
<p><span id="more-5046"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>I went to Applyzer and copy/pasted the top 100 free US apps from category &#8220;top overall&#8221; from iPhone and iPad into a graphic. Applyzer has the <a href="http://www.applyzer.com/?mmenu=top1000">top 1000</a> for for the following categories:</p>
<ul>
<li>Paid (iPhone/iPod)</li>
<li>Free (iPhone/iPod)</li>
<li>Grossing (iPhone/iPod)</li>
<li>Paid (iPad)</li>
<li>Free (iPad)</li>
<li>Grossing (iPad)</li>
<li>Paid (Mac)</li>
<li>Free (Mac)</li>
<li>Grossing (Mac)</li>
</ul>
<p>Then I went through the list and marked all apps that are showing as universal in iTunes. Then I searched where the same app would be in both ranks. Finally I made a quick survey if I could spot apps that had a separate iPhone and iPad version.</p>
<p>Note that this was done from hand and I might have missed a couple of connections. But even then I think the picture is rather obvious.</p>
<p><a href="http://www.cocoanetics.com/files/top100_comparison.jpg"><img class="size-large wp-image-5047 alignnone" title="Top100 Comparison iPhone/iPad" src="http://www.cocoanetics.com/files/top100_comparison-207x1024.jpg" alt="" width="207" height="1024" /></a></p>
<p>There were 27 universal apps in the free overall US top 100 and 33 in the iPad chart. Of these I could find 16 universal apps that where ranking similarily high in both charts. 11 universal iPhone apps did not show in the top 100 iPad chart. 14 universal iPad apps did not show in the top 100 iPhone/iPod chart. Possibly they were only slightly outside the top 100, I did not check.</p>
<p>The percentage of successful universal apps is an order of magnitude higher than dedicated versions. Amongst the top 100 (again only quickly looking visually) I could only find 4 apps that both had separate versions.</p>
<p>I invite your scrutiny of this casual analysis of mine, however I think that this graphic can only lead to this answer to Daniel&#8217;s question:</p>
<p>Make your free app universal, if you are NOT Rovio. I think this analysis debunks the myth that making a free app universal is bad for it&#8217;s ranking.</p>
<p>&nbsp;</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5046&amp;md5=985e89d1affe787dbf9ac6bc9d608f72" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/05/to-universal-or-not/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5046&amp;md5=985e89d1affe787dbf9ac6bc9d608f72" type="text/html" />"
	</item>
		<item>
		<title>Accessing the iOS System Log</title>
		<link>http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/</link>
		<comments>http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/#comments</comments>
		<pubDate>Thu, 10 Mar 2011 08:03:06 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4782</guid>
		<description><![CDATA[Peter Reinhardt asks: The app AppSwitch displays the console entries from NSLog logging in the iphone app. I tried to figure out how they do it but couldnt find an API. Do you have an idea? Intriguing question! My first gut reaction was that the guys from AppSwitch must have some magic sauce as I didn&#8217;t know of a way to access the console log on device like the Xcode organizer is able to. My first response was that probably they are doing some stderr bending as is possible with c++. But then I bought the app to see their trick with my own eyes. In this blog post I&#8217;ll show you how that&#8217;s done. Label Buy an ad here Readability Indeed, when I first launched the app there were several console messages from other apps, so they must have found a method to access these. I briefly looked at the contents of the log file directories, but /private/var/logs is not readable on device. Plain file reading is out of the question. The answer to the riddle is ASL, the Apple System Log facility. This is a low-level C API which is present on OSX as well as iOS and as such it has a man page. It turns out you can query the log for messages related to specific apps or just log the entire thing. A bit of experimentation and dipping into long past C-programming enabled me to come up with this code which takes all current log messages and converts them into a dictionary. aslmsg q, m; int i; const char *key, *val; &#160; q = asl_new&#40;ASL_TYPE_QUERY&#41;; &#160; aslresponse r = asl_search&#40;NULL, q&#41;; while &#40;NULL != &#40;m = aslresponse_next&#40;r&#41;&#41;&#41; &#123; NSMutableDictionary *tmpDict = &#91;NSMutableDictionary dictionary&#93;; &#160; for &#40;i = 0; &#40;NULL != &#40;key = asl_key&#40;m, i&#41;&#41;&#41;; i++&#41; &#123; NSString *keyString = &#91;NSString stringWithUTF8String:&#40;char *&#41;key&#93;; &#160; val = asl_get&#40;m, key&#41;; &#160; NSString *string = &#91;NSString stringWithUTF8String:val&#93;; &#91;tmpDict setObject:string forKey:keyString&#93;; &#125; &#160; NSLog&#40;@&#34;%@&#34;, tmpDict&#41;; &#125; aslresponse_free&#40;r&#41;; The necessary header asl.h can be included without having to add any extra framework. There are some interesting parts to be gleaned from the header. Did you &#8211; for example &#8211; know that there are more than 3 logging levels? Level 0 &#8211; &#8220;Emergency&#8221; Level 1 &#8211; &#8220;Alert&#8221; Level 2 &#8211; &#8220;Critical&#8221; Level 3 &#8211; &#8220;Error&#8221; Level 4 &#8211; &#8220;Warning&#8221; Level 5 &#8211; &#8220;Notice&#8221; Level 6 &#8211; &#8220;Info&#8221; Level 7 &#8211; &#8220;Debug&#8221; Since we are actually performing a search there are some nifty options to reduce the number of messages we are getting back. If I only want the messages of the app &#8220;Logger&#8221;, then I just add the following line after the asl_new: asl_set_query&#40;q, ASL_KEY_SENDER, &#34;Logger&#34;, ASL_QUERY_OP_EQUAL&#41;; To visualize, this is how an NSLog will look like You can see that there is a unix timestamp, Sender &#8220;Logger&#8221; is the name of my app and NSLog logs with level 4. Conclusion If you know how getting log messages is quite easy for somebody with a bit of C under his belt. For everybody else somebody should write an Objective-C wrapper. With the above knowledge several interesting usage scenarios suddenly become possible. For example one might want to add a mechanism to your apps to have users in need of support mail you the app logs. Or an framework like the Hockey ad-hoc distribution system might be able to provide access to log files similar to the crash reports you now get on iTunes Connect. In this article I only covered reading logs. However ASL also offers methods to LOG messages. So I can imagine somebody creating a replacement for NSLog with the ability of customizing your log messages. For example to set lower log levels for debug messages or to even add your own custom keys. Since AppSwitch is an approved app on the app store we can assume for the time being that using ASL to read the system log is deemed legal.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/"></g:plusone></div><p>Peter Reinhardt asks:</p>
<blockquote><p>The app AppSwitch displays the console entries from NSLog logging in the iphone app. I tried to figure out how they do it but couldnt find an API. Do you have an idea?</p></blockquote>
<p>Intriguing question! My first gut reaction was that the guys from <a href="http://itunes.apple.com/at/app/appswitch/id398317469?mt=8">AppSwitch</a> must have some magic sauce as I didn&#8217;t know of a way to access the console log on device like the Xcode organizer is able to. My first response was that probably they are doing some stderr bending as is possible with c++. But then I bought the app to see their trick with my own eyes.</p>
<p>In this blog post I&#8217;ll show you how that&#8217;s done.</p>
<p><span id="more-4782"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Indeed, when I first launched the app there were several console messages from other apps, so they must have found a method to access these.</p>
<p><a href="http://www.cocoanetics.com/files/Screenshot-2011.03.10-08.41.57.png"><img class="alignnone size-full wp-image-4784" title="Console Tab in AppSwitch" src="http://www.cocoanetics.com/files/Screenshot-2011.03.10-08.41.57.png" alt="" width="384" height="576" /></a></p>
<p>I briefly looked at the contents of the log file directories, but /private/var/logs is not readable on device. Plain file reading is out of the question.</p>
<p>The answer to the riddle is <strong>ASL</strong>, the Apple System Log facility. This is a low-level C API which is present on OSX as well as iOS and as such it has a <a href="https://developer.apple.com/library/ios/#documentation/System/Conceptual/ManPages_iPhoneOS/man3/asl.3.html">man page</a>. It turns out you can query the log for messages related to specific apps or just log the entire thing.</p>
<p>A bit of experimentation and dipping into long past C-programming enabled me to come up with this code which takes all current log messages and converts them into a dictionary.</p>

<div class="wp_codebox"><table><tr id="p478237"><td class="code" id="p4782code37"><pre class="objc" style="font-family:monospace;">aslmsg q, m;
<span style="color: #a61390;">int</span> i;
<span style="color: #a61390;">const</span> <span style="color: #a61390;">char</span> <span style="color: #002200;">*</span>key, <span style="color: #002200;">*</span>val;
&nbsp;
q <span style="color: #002200;">=</span> asl_new<span style="color: #002200;">&#40;</span>ASL_TYPE_QUERY<span style="color: #002200;">&#41;</span>;
&nbsp;
aslresponse r <span style="color: #002200;">=</span> asl_search<span style="color: #002200;">&#40;</span><span style="color: #a61390;">NULL</span>, q<span style="color: #002200;">&#41;</span>;
<span style="color: #a61390;">while</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NULL</span> <span style="color: #002200;">!=</span> <span style="color: #002200;">&#40;</span>m <span style="color: #002200;">=</span> aslresponse_next<span style="color: #002200;">&#40;</span>r<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> <span style="color: #002200;">*</span>tmpDict <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/"><span style="color: #400080;">NSMutableDictionary</span></a> dictionary<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span>i <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>; <span style="color: #002200;">&#40;</span><span style="color: #a61390;">NULL</span> <span style="color: #002200;">!=</span> <span style="color: #002200;">&#40;</span>key <span style="color: #002200;">=</span> asl_key<span style="color: #002200;">&#40;</span>m, i<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>; i<span style="color: #002200;">++</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>keyString <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">char</span> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>key<span style="color: #002200;">&#93;</span>;
&nbsp;
		val <span style="color: #002200;">=</span> asl_get<span style="color: #002200;">&#40;</span>m, key<span style="color: #002200;">&#41;</span>;
&nbsp;
		<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span><span style="color: #a61390;">string</span> <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> stringWithUTF8String<span style="color: #002200;">:</span>val<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>tmpDict setObject<span style="color: #002200;">:</span><span style="color: #a61390;">string</span> forKey<span style="color: #002200;">:</span>keyString<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, tmpDict<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span>
aslresponse_free<span style="color: #002200;">&#40;</span>r<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>The necessary header asl.h can be included without having to add any extra framework. There are some interesting parts to be gleaned from the header. Did you &#8211; for example &#8211; know that there are more than 3 logging levels?</p>
<ul>
<li>Level 0 &#8211; &#8220;Emergency&#8221;</li>
<li>Level 1 &#8211; &#8220;Alert&#8221;</li>
<li>Level 2 &#8211; &#8220;Critical&#8221;</li>
<li>Level 3 &#8211; &#8220;Error&#8221;</li>
<li>Level 4 &#8211; &#8220;Warning&#8221;</li>
<li>Level 5 &#8211; &#8220;Notice&#8221;</li>
<li>Level 6 &#8211; &#8220;Info&#8221;</li>
<li>Level 7 &#8211; &#8220;Debug&#8221;</li>
</ul>
<p>Since we are actually performing a search there are some nifty options to reduce the number of messages we are getting back. If I only want the messages of the app &#8220;Logger&#8221;, then I just add the following line after the asl_new:</p>

<div class="wp_codebox"><table><tr id="p478238"><td class="code" id="p4782code38"><pre class="objc" style="font-family:monospace;">asl_set_query<span style="color: #002200;">&#40;</span>q, ASL_KEY_SENDER, <span style="color: #bf1d1a;">&quot;Logger&quot;</span>, ASL_QUERY_OP_EQUAL<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>To visualize, this is how an NSLog will look like</p>
<p><a href="http://www.cocoanetics.com/files/Screen-shot-2011-03-10-at-8.54.13-AM.png"><img class="alignnone size-full wp-image-4785" title="NSLog in asl" src="http://www.cocoanetics.com/files/Screen-shot-2011-03-10-at-8.54.13-AM.png" alt="" width="396" height="190" /></a></p>
<p>You can see that there is a unix timestamp, Sender &#8220;Logger&#8221; is the name of my app and NSLog logs with level 4.</p>
<h3>Conclusion</h3>
<p>If you know how getting log messages is quite easy for somebody with a bit of C under his belt. For everybody else somebody should write an Objective-C wrapper.</p>
<p>With the above knowledge several interesting usage scenarios suddenly become possible. For example one might want to add a mechanism to your apps to have users in need of support mail you the app logs. Or an framework like the Hockey ad-hoc distribution system might be able to provide access to log files similar to the crash reports you now get on iTunes Connect.</p>
<p>In this article I only covered reading logs. However ASL also offers methods to LOG messages. So I can imagine somebody creating a replacement for NSLog with the ability of customizing your log messages. For example to set lower log levels for debug messages or to even add your own custom keys.</p>
<p>Since AppSwitch is an approved app on the app store we can assume for the time being that using ASL to read the system log is deemed legal.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4782&amp;md5=4d07f0b71646da40a78aba92ab47b5a7" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4782&amp;md5=4d07f0b71646da40a78aba92ab47b5a7" type="text/html" />"
	</item>
		<item>
		<title>JSON versus PLIST, the Ultimate Showdown</title>
		<link>http://www.cocoanetics.com/2011/03/json-versus-plist-the-ultimate-showdown/</link>
		<comments>http://www.cocoanetics.com/2011/03/json-versus-plist-the-ultimate-showdown/#comments</comments>
		<pubDate>Wed, 09 Mar 2011 12:24:26 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4771</guid>
		<description><![CDATA[Communicating with web services you have to decide on a way to transport the date back and forth. Recently &#8211; with the help of the popular Twitter-API &#8211; JSON seems to have come ahead in the race. Other contenders are property lists and XML. Property Lists (PLISTs) are available in XML-Text and a binary (&#8220;old&#8221;) format and are widely supported in the Apple APIs which makes them a joy to work with. JSON files on the other hand are easy to be generated server-side as they are basically just concatenated text, much less verbose than pure XML. The binary alternative might also be a contender when it comes to performance in transmission and parsing, provided some component is installed on the server to generate them. In this blog article we are trying to answer the question once and for all what you should use in your own apps. Label Buy an ad here Readability Martin Brugger from Austrian iOS development company BytePoets spent a lot of time researching the hard facts for us, so that we have a solid base for our analysis. In part this work is based on what Sam Soffes previously published on the performance of a variety of JSON benchmarks. He created a new GitHub project for his benchmarks which are using all the latest version of all JSON toolkits from where you can check out the code for yourself. These experiments specifically excluded raw XML parsing because the NSXMLParser that comes with iOS is using the sequential SAX method and thus the results cannot be easily compared to JSON and PLIST which take in text and output NSDictionary or NSArray objects. Most of the data types in JSON and all of the ones in PLISTs map to typed Objective-C objects, in contrast to XML where you don&#8217;t have such a built in schema. Thus pure XML might be more flexible, but at the same time you have to jump through hoops to get strong typing. It&#8217;s a non-starter in today&#8217;s race. So the contestors in our race where: YAJL JSONKit TouchJSON JSON Framework Apple&#8217;s JSON Framework (private) Property List (XML) Property List (Binary) One interesting thing that Soffes had uncovered was that Apple indeed has their own highly performant private API for parsing JSON. Sam reconstructed the necessary headers and so it&#8217;s another interesting contender to see here, even though we are not allowed to use the JSON.framework in our app store apps. Pity, it&#8217;s quite fast. The amazing race To get even more relevant data Brugger benchmarked the serialization and deserialization of an array and a dictionary of 1000 entries each) and the standard Twitter JSON. Since the latter cannot be mappted into property lists, this test was excluded for PLISTs. Here are the writing results, shorter bars are better. As you can see there is a wide variety between the various toolkits. Arrays, Dictionaries and Twitter&#8217;s JSON take varying amounts of time to process. We immediately see the winner: JSONKit, which was just recently updated to version 1.4. Second place goes to property lists, where &#8211; curiously &#8211; there is almost no difference between the binary and XML formats. Then there is the JSON Framework on the third spot, winning over the private Apple API ever so slightly. I get the feeling that the low level optimization work that&#8217;s been put into JSONKit as well as being carried out by smart Apple engineers is responsible for this result. Let&#8217;s have a look at the reading performance. This is probably the more important one of both benchmarks since most of the data on your mobile device will be received and consumed. Here the verdict is a little more complex than just stating places. Just as with the writing benchmarks arrays are generally quicker to process. This part is again clearly won by JSONKit, closely followed by binary PLIST. Third place is split between YaJL and Apple JSON. If the consumed data is a big dictionary the clear winner is the binary property list, followed by JSONKit and Apple JSON. YAJL and XML PLIST share the forth place. When it comes to &#8220;real life&#8221; scenarios &#8211; like parsing the Twitter JSON &#8211; property lists cannot compete unfortunately, so here&#8217;s another clear win for JSONKit. This is by a wide margin as the second YAJL and the third Apple JSON are orders of magnitude slower. Does size matter? Now another question we set out to answer revolves around the time it takes for JSON or PLIST data to be transferred to the client. This is a function of the size, the smaller it is even without compression, the faster it has travelled over the pipe. My hunch was that binary PLISTs would be way smaller then everything else, but I was proven wrong as you can [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2011/03/json-versus-plist-the-ultimate-showdown/"></g:plusone></div><p>Communicating with web services you have to decide on a way to transport the date back and forth. Recently &#8211; with the help of the popular Twitter-API &#8211; <a href="http://www.json.org/">JSON</a> seems to have come ahead in the race. Other contenders are property lists and XML. Property Lists (PLISTs) are available in XML-Text and a binary (&#8220;old&#8221;) format and are widely supported in the Apple APIs which makes them a joy to work with.</p>
<p>JSON files on the other hand are easy to be generated server-side as they are basically just concatenated text, much less verbose than pure XML. The binary alternative might also be a contender when it comes to performance in transmission and parsing, provided some component is installed on the server to generate them.</p>
<p>In this blog article we are trying to answer the question once and for all what you should use in your own apps.</p>
<p><span id="more-4771"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Martin Brugger from Austrian iOS development company <a href="http://www.cocoapedia.org/wiki/BytePoets">BytePoets</a> spent a lot of time researching the hard facts for us, so that we have a solid base for our analysis. In part this work is based on what Sam Soffes previously <a href="http://samsoff.es/posts/updated-iphone-json-benchmarks">published</a> on the performance of a variety of JSON benchmarks. He created a new <a href="https://github.com/mbrugger/json-benchmarks/">GitHub project for his benchmarks</a> which are using all the latest version of all JSON toolkits from where you can check out the code for yourself.</p>
<p>These experiments specifically excluded raw XML parsing because the NSXMLParser that comes with iOS is using the sequential SAX method and thus the results cannot be easily compared to JSON and PLIST which take in text and output NSDictionary or NSArray objects. Most of the data types in JSON and all of the ones in PLISTs map to typed Objective-C objects, in contrast to XML where you don&#8217;t have such a built in schema. Thus pure XML might be more flexible, but at the same time you have to jump through hoops to get strong typing. It&#8217;s a non-starter in today&#8217;s race.</p>
<p>So the contestors in our race where:</p>
<ul>
<li>YAJL</li>
<li>JSONKit</li>
<li>TouchJSON</li>
<li>JSON Framework</li>
<li>Apple&#8217;s JSON Framework (private)</li>
<li>Property List (XML)</li>
<li>Property List (Binary)</li>
</ul>
<p>One interesting thing that Soffes had uncovered was that Apple indeed has their own highly performant <a href="http://samsoff.es/posts/parsing-json-with-the-iphones-private-json-framework">private API for parsing JSON</a>. Sam reconstructed the necessary headers and so it&#8217;s another interesting contender to see here, even though we are not allowed to use the JSON.framework in our app store apps. Pity, it&#8217;s quite fast.</p>
<h3>The amazing race</h3>
<p>To get even more relevant data Brugger benchmarked the serialization and deserialization of an array and a dictionary of 1000 entries each) and the standard Twitter JSON. Since the latter cannot be mappted into property lists, this test was excluded for PLISTs.</p>
<p>Here are the writing results, shorter bars are better.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-2.34.58-PM.png"><img class="alignnone size-full wp-image-4777" title="Benchmark Writing" src="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-2.34.58-PM.png" alt="" width="685" height="196" /></a></p>
<p>As you can see there is a wide variety between the various toolkits. Arrays, Dictionaries and Twitter&#8217;s JSON take varying amounts of time to process. We immediately see the winner: JSONKit, which was just recently updated to version 1.4. Second place goes to property lists, where &#8211; curiously &#8211; there is almost no difference between the binary and XML formats. Then there is the JSON Framework on the third spot, winning over the private Apple API ever so slightly.</p>
<p>I get the feeling that the low level optimization work that&#8217;s been put into JSONKit as well as being carried out by smart Apple engineers is responsible for this result.</p>
<p>Let&#8217;s have a look at the reading performance. This is probably the more important one of both benchmarks since most of the data on your mobile device will be received and consumed. Here the verdict is a little more complex than just stating places. Just as with the writing benchmarks arrays are generally quicker to process. This part is again clearly won by JSONKit, closely followed by binary PLIST. Third place is split between YaJL and Apple JSON.</p>
<p>If the consumed data is a big dictionary the clear winner is the binary property list, followed by JSONKit and Apple JSON. YAJL and XML PLIST share the forth place.</p>
<p><a href="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-2.35.07-PM.png"><img class="alignnone size-full wp-image-4778" title="Benchmark Reading" src="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-2.35.07-PM.png" alt="" width="704" height="223" /></a></p>
<p>When it comes to &#8220;real life&#8221; scenarios &#8211; like parsing the Twitter JSON &#8211; property lists cannot compete unfortunately, so here&#8217;s another clear win for JSONKit. This is by a wide margin as the second YAJL and the third Apple JSON are orders of magnitude slower.</p>
<h3>Does size matter?</h3>
<p>Now another question we set out to answer revolves around the time it takes for JSON or PLIST data to be transferred to the client. This is a function of the size, the smaller it is even without compression, the faster it has travelled over the pipe.</p>
<p>My hunch was that binary PLISTs would be way smaller then everything else, but I was proven wrong as you can see from the following chart:</p>
<p><a href="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-1.06.35-PM.png"><img class="alignnone size-full wp-image-4774" title="File format comparison" src="http://www.cocoanetics.com/files/Screen-shot-2011-03-09-at-1.06.35-PM.png" alt="" width="721" height="664" /></a></p>
<p>The NSArray is a third larger expressed as XML PLIST than as JSON, the NSDictionary is even twice as large. The binary PLIST is about the same, so much less of a dramatic difference than I had expected.</p>
<h3>Conclusion</h3>
<p>In terms of transfer speed any plain-text format like XML or XML Plist loses against the compactness of JSON or binary PLISTs. But as stated earlier the difference between BPLIST and JSON can be disregarded because there almost is none.</p>
<p>In all tests JSONKit was the clear winner or came pretty close to it. It really depends on the specifics of your own project whether you would best use this or Apple&#8217;s binary PLIST format. If you are coding multi-platform then it would probably be smarter to go for JSON because the binary PLIST format is not widely used on any other platforms than iOS or OSX. In contrast if you can afford the luxury of only targeting Apple platforms then binary PLIST is just as good a choice, provided you can install the components necessary on your server to be able to output it there.</p>
<p>For all other intents and purposes you can think of JSONKit and binary property lists as identical in transfer and processing speeds. Thanks to the amazing tuning that went into both.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4771&amp;md5=f3a1e80ac398ef0a6d8891f1e23f4454" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2011/03/json-versus-plist-the-ultimate-showdown/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4771&amp;md5=f3a1e80ac398ef0a6d8891f1e23f4454" type="text/html" />"
	</item>
		<item>
		<title>Bars Like the New York Times App</title>
		<link>http://www.cocoanetics.com/2010/12/bars-like-the-new-york-times-app/</link>
		<comments>http://www.cocoanetics.com/2010/12/bars-like-the-new-york-times-app/#comments</comments>
		<pubDate>Thu, 23 Dec 2010 08:30:03 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=4511</guid>
		<description><![CDATA[Elias Sanchez asks: Hello Oliver. Quick? Do you have any tips in making a toolbar appear/disappear? Trying to mimic what the NYT app does when looking at an article. Is it using Core Animation perhaps? Can&#8217;t find anything out there. Any ideas? ThxU Looking at the NYT App you can see that they do quite a bit of manipulation of the bars of which there are 3: Tab Bar, Navigation Bar and sometimes a Tool Bar. For beginning iOS Developers it might seem daunting to combine all of these for the effect that the NYT App achieves. In this article I give you an analysis of what they did so that you have their techniques at your disposal, too. Label Buy an ad here Readability Let&#8217;s start out by investigating how the basic navigation views are laid out. At its root the app has a tab bar (Latest, Popular, Saved, Search, More). Each of the tabs has its own view controller stack. To get the navigation bar and table navigation these tab view controllers have to be navigation controllers with table view controllers as first element on their stack. You can imagine this like several stacks next to each other where each stack belongs to one tab in the tab bar controller. Because of this, if you navigate around on one tab, the contents of the other tabs are not affected. So the front page of the article list is a tableview controller (with a header view &#8220;Most E-Mailed&#8221;) in a navigation controller in a tab bar controller. You see the hierarchy in front of your mental eye? Now if you tap on an article several things happen at the same time: The tab bar at the bottom slides to the left, together with the article list The navigation bar becomes translucent A toobar slides in from the bottom The same happens in reverse if you go back. You can hide and unhide both the navigation bar and the toolbar by tapping on the screen while the article always fills the entire view. As a geeky detail there is an ad banner riding on the top of the toolbar and moving with it. First the Bars For this tutorial you would prepare a tab bar application from the project template. Then you would remove the FirstViewController and replace it with a UINavigationController which gets a UITableViewController as first child. You can download the project here: NYTBars. Have a look at the MainWindow.xib to see this layout. The following code will perform the hiding and sliding on the individual article view controller: - &#40;void&#41;viewDidLoad &#123; &#91;super viewDidLoad&#93;; &#160; UIBarButtonItem *item = &#91;&#91;&#91;UIBarButtonItem alloc&#93; initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector&#40;add:&#41;&#93; autorelease&#93;; &#91;self setToolbarItems:&#91;NSArray arrayWithObject:item&#93;&#93;; &#125; &#160; - &#40;void&#41;viewWillAppear:&#40;BOOL&#41;animated &#123; &#91;super viewWillAppear:animated&#93;; &#160; &#91;self.navigationController setToolbarHidden:NO animated:YES&#93;; self.navigationController.toolbar.barStyle = UIBarStyleBlackTranslucent; self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent; &#125; &#160; - &#40;void&#41;viewWillDisappear:&#40;BOOL&#41;animated &#123; &#91;super viewWillDisappear:animated&#93;; &#160; &#91;self.navigationController setToolbarHidden:YES animated:YES&#93;; self.navigationController.toolbar.barStyle = UIBarStyleBlack; self.navigationController.navigationBar.barStyle = UIBarStyleBlack; &#125; In viewDidLoad we are setting up the items for the toolbar. The toolbar itself is owned by the view controller&#8217;s navigation controller i.e. the UINavigationController that this view controller is currently on. But the items you specify via the view controller&#8217;s setToolbarItems. These are local to the view controller and every view controller can set it&#8217;s own toolbar items. If I&#8217;m not mistaken then this methodology was introduced with iOS 3.0. Before that you had to manage the toolbar yourself. If we look closely at the transition from article list to individual article we see that the animations occur during the slide. This is why we put the showing and hiding in the WILL delegate methods. If we wanted the animations to happen after the slide in then we would instead use the DID methods. viewWillAppear is triggered as soon as the view controller is pushed on the navigation controller and before the animation is over. So you see how we change the bar style between translucent and opaque and how we show/hide the toolbar with animated:YES. We don&#8217;t tell the article view controller that it wantsFullScreenLayout, because this would cause the view to be under the status bar as well, but the same principle would work for hiding this as well. One thing though: the tab bar sticks around still, so &#8211; before pushing the article view controller &#8211; we need to tell it that it will also hide the tab bar. The property in question is called hidesBottomBarWhenPushed, admittedly not really intuitive. The &#8220;bottom bar&#8221; should rather be called &#8220;tab bar&#8221; in my opinion. I put it in the initWithNibName, but any place before the pushing is fine: self.hidesBottomBarWhenPushed = YES; Previously I had this setting right be fore pushViewController but I prefer to put these things into the objects themselves where possible. Tap to Hide To get the interactivity i.e. ability to hide the bars [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/12/bars-like-the-new-york-times-app/"></g:plusone></div><p>Elias Sanchez asks:</p>
<blockquote><p>Hello Oliver. Quick? Do you have any tips in making a toolbar appear/disappear? Trying to mimic what the NYT app does when looking at an article. Is it using Core Animation perhaps? Can&#8217;t find anything out there. Any ideas? ThxU</p></blockquote>
<p>Looking at the <a href="http://itunes.apple.com/us/app/nytimes/id284862083?mt=8">NYT App</a> you can see that they do quite a bit of manipulation of the bars of which there are 3: Tab Bar, Navigation Bar and sometimes a Tool Bar.</p>
<p>For beginning iOS Developers it might seem daunting to combine all of these for the effect that the NYT App achieves. In this article I give you an analysis of what they did so that you have their techniques at your disposal, too.</p>
<p><span id="more-4511"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Let&#8217;s start out by investigating how the basic navigation views are laid out.</p>
<p><a href="http://www.cocoanetics.com/files/mzl.rrkyqrpp.320x480-75.jpg"><img class="alignnone size-full wp-image-4512" title="NYT App Article List" src="http://www.cocoanetics.com/files/mzl.rrkyqrpp.320x480-75.jpg" alt="" width="224" height="336" /></a> <a href="http://www.cocoanetics.com/files/mzl.hvolfmqo.320x480-75.jpg"><img class="alignnone size-full wp-image-4513" title="NYT App Individual Article" src="http://www.cocoanetics.com/files/mzl.hvolfmqo.320x480-75.jpg" alt="" width="224" height="336" /></a></p>
<p>At its root the app has a tab bar (Latest, Popular, Saved, Search, More). Each of the tabs has its own view controller stack. To get the navigation bar and table navigation these tab view controllers have to be navigation controllers with table view controllers as first element on their stack.</p>
<p>You can imagine this like several stacks next to each other where each stack belongs to one tab in the tab bar controller. Because of this, if you navigate around on one tab, the contents of the other tabs are not affected.</p>
<p>So the front page of the article list is a tableview controller (with a header view &#8220;Most E-Mailed&#8221;) in a navigation controller in a tab bar controller. You see the hierarchy in front of your mental eye?</p>
<p>Now if you tap on an article several things happen at the same time:</p>
<ul>
<li>The tab bar at the bottom slides to the left, together with the article list</li>
<li>The navigation bar becomes translucent</li>
<li>A toobar slides in from the bottom</li>
</ul>
<p>The same happens in reverse if you go back. You can hide and unhide both the navigation bar and the toolbar by tapping on the screen while the article always fills the entire view. As a geeky detail there is an ad banner riding on the top of the toolbar and moving with it.</p>
<h3>First the Bars</h3>
<p>For this tutorial you would prepare a tab bar application from the project template. Then you would remove the FirstViewController and replace it with a UINavigationController which gets a UITableViewController as first child. You can download the project here: <a href="http://www.cocoanetics.com/files/NYTBars.zip">NYTBars</a>. Have a look at the MainWindow.xib to see this layout.</p>
<p>The following code will perform the hiding and sliding on the individual article view controller:</p>

<div class="wp_codebox"><table><tr id="p451144"><td class="code" id="p4511code44"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
	UIBarButtonItem <span style="color: #002200;">*</span>item <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIBarButtonItem alloc<span style="color: #002200;">&#93;</span>
			initWithBarButtonSystemItem<span style="color: #002200;">:</span>UIBarButtonSystemItemAdd
			target<span style="color: #002200;">:</span>self
			action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>add<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self setToolbarItems<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/"><span style="color: #400080;">NSArray</span></a> arrayWithObject<span style="color: #002200;">:</span>item<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>super viewWillAppear<span style="color: #002200;">:</span>animated<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self.navigationController setToolbarHidden<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	self.navigationController.toolbar.barStyle <span style="color: #002200;">=</span> UIBarStyleBlackTranslucent;
	self.navigationController.navigationBar.barStyle <span style="color: #002200;">=</span> UIBarStyleBlackTranslucent;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillDisappear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span>super viewWillDisappear<span style="color: #002200;">:</span>animated<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>self.navigationController setToolbarHidden<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span> animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	self.navigationController.toolbar.barStyle <span style="color: #002200;">=</span> UIBarStyleBlack;
	self.navigationController.navigationBar.barStyle <span style="color: #002200;">=</span> UIBarStyleBlack;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>In viewDidLoad we are setting up the items for the toolbar. The toolbar itself is owned by the view controller&#8217;s navigation controller i.e. the UINavigationController that this view controller is currently on. But the items you specify via the view controller&#8217;s setToolbarItems. These are local to the view controller and every view controller can set it&#8217;s own toolbar items. If I&#8217;m not mistaken then this methodology was introduced with iOS 3.0. Before that you had to manage the toolbar yourself.</p>
<p>If we look closely at the transition from article list to individual article we see that the animations occur during the slide. This is why we put the showing and hiding in the WILL delegate methods. If we wanted the animations to happen after the slide in then we would instead use the DID methods. viewWillAppear is triggered as soon as the view controller is pushed on the navigation controller and before the animation is over.</p>
<p>So you see how we change the bar style between translucent and opaque and how we show/hide the toolbar with animated:YES. We don&#8217;t tell the article view controller that it wantsFullScreenLayout, because this would cause the view to be under the status bar as well, but the same principle would work for hiding this as well.</p>
<p>One thing though: the tab bar sticks around still, so &#8211; before pushing the article view controller &#8211; we need to tell it that it will also hide the tab bar. The property in question is called hidesBottomBarWhenPushed, admittedly not really intuitive. The &#8220;bottom bar&#8221; should rather be called &#8220;tab bar&#8221; in my opinion. I put it in the initWithNibName, but any place before the pushing is fine:</p>

<div class="wp_codebox"><table><tr id="p451145"><td class="code" id="p4511code45"><pre class="objc" style="font-family:monospace;">self.hidesBottomBarWhenPushed <span style="color: #002200;">=</span> <span style="color: #a61390;">YES</span>;</pre></td></tr></table></div>

<p>Previously I had this setting right be fore pushViewController but I prefer to put these things into the objects themselves where possible.</p>
<h3>Tap to Hide</h3>
<p>To get the interactivity i.e. ability to hide the bars we use a tap gesture recognizer which we attach to the view in viewDidLoad and wire up some more hiding/showing.</p>

<div class="wp_codebox"><table><tr id="p451146"><td class="code" id="p4511code46"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad <span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// other inits omitted</span>
&nbsp;
	UITapGestureRecognizer <span style="color: #002200;">*</span>gesture <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UITapGestureRecognizer alloc<span style="color: #002200;">&#93;</span> 
			initWithTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>tapped<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self.view addGestureRecognizer<span style="color: #002200;">:</span>gesture<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>gesture release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tapped<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITapGestureRecognizer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>gesture
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">BOOL</span> barsHidden <span style="color: #002200;">=</span> self.navigationController.navigationBar.hidden;
&nbsp;
	<span style="color: #002200;">&#91;</span>self.navigationController setToolbarHidden<span style="color: #002200;">:!</span>barsHidden animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self.navigationController setNavigationBarHidden<span style="color: #002200;">:!</span>barsHidden animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This makes for the nice effect to switch between full-screen reading and access to tools or the back button.</p>
<h3>Bonus Section: Ad Riding on Toolbar</h3>
<p>The toolbar is just a UIToolbar which descends from UIView. For performance reasons the default setting is to not clip subviews. Therefore we might be tempted to add our ad banner like this to the toolbar:</p>

<div class="wp_codebox"><table><tr id="p451147"><td class="code" id="p4511code47"><pre class="objc" style="font-family:monospace;">UIView <span style="color: #002200;">*</span>simulatedAd <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">-</span><span style="color: #2400d9;">30</span>, <span style="color: #2400d9;">320</span>, <span style="color: #2400d9;">30</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
simulatedAd.backgroundColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>self.navigationController.toolbar addSubview<span style="color: #002200;">:</span>simulatedAd<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>This works, but only while the toolbar is visible. iOS hides the toolbar and by extension all of its subviews when it goes off screen. It does not check whether a non-clipped child view would still be visible. This causes the ad view to disappear as well. Not the affect we were shooting for.</p>
<p>Instead we need to position the add as subview of the article view controller and move it in synchronized fashion whenever the toolbar moves.</p>
<p>How about some fancy pants KVO (Key Value Observing)? Nope, won&#8217;t work. No KVO event triggers on key &#8220;frame&#8221; and the bounds of the toolbar don&#8217;t change even though KVO triggers on &#8220;bounds&#8221; every time the bar moves. And since there is no notification to my knowledge that would inform us about the bar moving this leaves us with only one option: move it ourselves and time it to be in sync with the bar.</p>
<p>Since we know exactly when the bar is coming or going we can simply animated the frame of the ad banner for the same distance and duration. Apple provides the UINavigationControllerHideShowBarDuration constant which gives us the exact timing.</p>

<div class="wp_codebox"><table><tr id="p451148"><td class="code" id="p4511code48"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// ...</span>
&nbsp;
	<span style="color: #11740a; font-style: italic;">// the +15 is a mystery to me</span>
	simulatedAd <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, 
			self.view.bounds.size.height<span style="color: #002200;">+</span><span style="color: #2400d9;">15</span>, <span style="color: #2400d9;">320</span>, <span style="color: #2400d9;">30</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span> autorelease<span style="color: #002200;">&#93;</span>;
	simulatedAd.backgroundColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIColor blueColor<span style="color: #002200;">&#93;</span>;
	simulatedAd.autoresizingMask <span style="color: #002200;">=</span> UIViewAutoresizingFlexibleTopMargin;
	<span style="color: #002200;">&#91;</span>self.view addSubview<span style="color: #002200;">:</span>simulatedAd<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>positionAdUp<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>up animated<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	CGRect frame <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, self.view.bounds.size.height<span style="color: #002200;">-</span><span style="color: #2400d9;">30</span>, <span style="color: #2400d9;">320</span>, <span style="color: #2400d9;">30</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>up<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		frame.origin.y <span style="color: #002200;">-=</span> self.navigationController.toolbar.bounds.size.height;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>animated<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>UIView beginAnimations<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> context<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span><span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span>UIView setAnimationDuration<span style="color: #002200;">:</span>UINavigationControllerHideShowBarDuration<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
	simulatedAd.frame <span style="color: #002200;">=</span> frame;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>animated<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>UIView commitAnimations<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// ...</span>
	<span style="color: #002200;">&#91;</span>self positionAdUp<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span> animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidAppear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// ...</span>
	<span style="color: #002200;">&#91;</span>self positionAdUp<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span> animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewWillDisappear<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>animated
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// ...</span>
	<span style="color: #002200;">&#91;</span>self positionAdUp<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span>
&nbsp;
<span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>tapped<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UITapGestureRecognizer <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>gesture
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// ...</span>
	<span style="color: #002200;">&#91;</span>self positionAdUp<span style="color: #002200;">:</span>barsHidden animated<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Like this we can animate the ad around or by calling the positionAdUp method with animated:NO it would pop there. If you didn&#8217;t want the ad to already show on slide in, then you could pop it in in viewDidAppear or after the ad is loaded from server.</p>
<p>With this the ad is always perfectly synchronized with the bar. I discovered the +15 in the init through trial and error with <a href="http://mschrag.github.com/">slowmo</a> though I cannot explain how this is calculated. For all other other frame moving I&#8217;m subtracting the ad banner height from the view height and it fits. If you can come up with a good explanation, let me know in the comments.</p>
<h3>Conclusion</h3>
<p>If you know how that mimicking the NYT App&#8217;s UI is a breeze. Personally I would not put so much UI changes into the user&#8217;s face. Especially the hiding of the tab bar in tandem with sliding in a toolbar looks awkward to me. You could just as well wait with the toolbar until the navigation animation is over and then slide it in. Less lines crossing over each other.</p>
<p>As usual, if you read this article to it&#8217;s and and learned something from it, then I would like to encourage you to use the Flattr button below to show your appreciation or the social bookmarking feature to share this article with your developer colleagues.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4511&amp;md5=71dcdc65ca5acad8765a95e974c10fb0" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/12/bars-like-the-new-york-times-app/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=4511&amp;md5=71dcdc65ca5acad8765a95e974c10fb0" type="text/html" />"
	</item>
		<item>
		<title>How to become GREAT at iOS Development</title>
		<link>http://www.cocoanetics.com/2010/07/how-to-become-great-at-ios-development/</link>
		<comments>http://www.cocoanetics.com/2010/07/how-to-become-great-at-ios-development/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 07:05:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=2848</guid>
		<description><![CDATA[I&#8217;m interested in getting your questions because answering them helps me structure the material in my head. And there&#8217;s a saying that &#8220;what you teach you learn&#8221;, because of that. Devin Snipes, an aspiring young iOS Developer asks: Hello Dr. Touch, My name is Devin Snipes, I&#8217;m 15 years old and I&#8217;m an iPhone Developer. I&#8217;ve been following your work for a little less than a year, and I&#8217;ve grown to love it. Your work is amazing, and I hope to someday be as good as you are in programming for the iOS platform. I currently have a few iPhone applications on the AppStore, but nothing compared to yours. I&#8217;d like to ask you a few questions that will hopefully give me more insight on your developmental skills and how I can improve on my skill. Well, &#8220;You catch more flies with honey than vinegar&#8221;. If somebody asks so nicely I&#8217;ll usually try to respond with something useful. 1. How did you become so great at programming for the iPhone? I&#8217;m doing it full time only since last December. And before that I was looking at code on most days for a couple of hours. Do you know the rule of 10,000? It says that if you want to be world-class in any field you have to invest 10,000 hours in total. Before I got into developing for the iPhone I was collecting programming time for many years. So I probably reached 10,000 a while ago. But that&#8217;s not strictly Cocoa time. At 10 hours a day it takes you around 3 years to reach 10,000. So I&#8217;m probably around 5,000 hours doing iPhone stuff. Label Buy an ad here Readability That makes me an intermediary iOS Developer with good analytics and good abstraction skills. Not yet a real expert, but (working on) getting there. There are people who are more &#8220;expert&#8221; than myself, the stars of Cocoa, if you will. Check out how their bylines describe the place that iOS development has taken in their life. Matt Legend Gammell (&#8220;Instinctive Code&#8221;) Marcus Zarra (&#8220;Cocoa is my Girlfriend&#8221;) Matt Gallagher (&#8220;Cocoa with Love&#8221;) Aaron Hillegass (&#8220;Big Nerd Ranch&#8221;) My trick is to vary the time I can log towards this goal. I&#8217;m not only programming, I&#8217;m also watching training videos, doing coaching, teaching development courses, troubleshooting in other people&#8217;s apps, making encapsulated software components that I&#8217;m selling, I have some apps of my own and lots of contract work. The latter in itself is only partially coding because you also have to train your brain in how to put people&#8217;s ideas and specifications into code. If you program hours and hours on end then you also begin to come up with ways how to use your time more effectively. Like for example putting together a set of tools and utility classes that you are using all the time to quickly achieve standard tasks. Take it one level higher and then you are writing software components that can be plugged into your own apps or even other people&#8217;s apps. Writing reusable code not only makes your life easier, it also forces you to think through and abstract interfaces such that your components are loosely coupled. That&#8217;s the essence of MVC (Model-View-Controller), the heart of Cocoa. And some other activities that are only peripheral like blogging and podcasting. But I find that as long as you center it on a single topic then all your activities cross-pollinate. That&#8217;s why I gave up on Windows support or programming for any other platform than iOS. And I find that by writing about programming it forces me to chew through boring documentation and try out the techniques I&#8217;m covering. This META level of Cocoa Coding teaches me just as well as my readers. Obviously it helps if you can do it full-time, that&#8217;s why I detailed this multi-prong strategy in my previous blog article Business as Unusual. 2. Who made the shirt you were wearing in your iPhone 4 unboxing video? It was given to me last Christmas by my brother-in-law who has a friend who has the tools to make T-Shirts. Do you think I should start a line of Dr. Touch merchandising items? 3. This might be going a little over-board, but do you mind taking a look at a few of my current iPhone &#38; iPad applications and tell me how I could improve them? I&#8217;d really appreciate it if you took the time to look over them and give me your diagnosis on how they can be improved or fixed up. I&#8217;m only judging what I see on the app store and those are just my first gut responses. If you have a minute to look at these apps too then please add your feedback in the comments. uChat for iPhone [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/07/how-to-become-great-at-ios-development/"></g:plusone></div><p>I&#8217;m interested in getting your questions because answering them helps me structure the material in my head. And there&#8217;s a saying that &#8220;what you teach you learn&#8221;, because of that.</p>
<p><a href="http://itunes.com/apps/devinsnipes">Devin Snipes</a>, an aspiring young iOS Developer asks:</p>
<blockquote><p>Hello Dr. Touch,</p>
<p>My name is Devin Snipes, I&#8217;m 15 years old and I&#8217;m an iPhone Developer. I&#8217;ve been following your work for a little less than a year, and I&#8217;ve grown to love it. Your work is amazing, and I hope to someday be as good as you are in programming for the iOS platform. I currently have a few iPhone applications on the AppStore, but nothing compared to yours.</p>
<p>I&#8217;d like to ask you a few questions that will hopefully give me more insight on your developmental skills and how I can improve on my skill.</p></blockquote>
<p>Well, &#8220;You catch more flies with honey than vinegar&#8221;. If somebody asks so nicely I&#8217;ll usually try to respond with something useful.</p>
<blockquote><p>1. How did you become so great at programming for the iPhone?</p></blockquote>
<p>I&#8217;m doing it full time only since last December. And before that I was looking at code on most days for a couple of hours. Do you know the rule of 10,000? It says that if you want to be world-class in any field you have to invest 10,000 hours in total. Before I got into developing for the iPhone I was collecting programming time for many years. So I probably reached 10,000 a while ago. But that&#8217;s not strictly Cocoa time. At 10 hours a day it takes you around 3 years to reach 10,000. So I&#8217;m probably around 5,000 hours doing iPhone stuff.</p>
<p><span id="more-2848"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>That makes me an intermediary iOS Developer with good analytics and good abstraction skills. Not yet a real expert, but (working on) getting there. There are people who are more &#8220;expert&#8221; than myself, the stars of Cocoa, if you will. Check out how their bylines describe the place that iOS development has taken in their life.</p>
<ul>
<li><a href="http://mattgemmell.com/">Matt Legend Gammell</a> (&#8220;Instinctive Code&#8221;)</li>
<li><a href="http://www.cimgf.com/">Marcus Zarra</a> (&#8220;Cocoa is my Girlfriend&#8221;)</li>
<li><a href="http://cocoawithlove.com">Matt Gallagher</a> (&#8220;Cocoa with Love&#8221;)</li>
<li><a href="http://www.bignerdranch.com/instructors/hillegass.shtml">Aaron Hillegass</a> (&#8220;Big Nerd Ranch&#8221;)</li>
</ul>
<p>My trick is to vary the time I can log towards this goal. I&#8217;m not only programming, I&#8217;m also watching training videos, doing coaching, teaching development courses, troubleshooting in other people&#8217;s apps, making encapsulated software components that I&#8217;m selling, I have some apps of my own and lots of contract work. The latter in itself is only partially coding because you also have to train your brain in how to put people&#8217;s ideas and specifications into code.</p>
<p>If you program hours and hours on end then you also begin to come up with ways how to use your time more effectively. Like for example putting together a set of tools and utility classes that you are using all the time to quickly achieve standard tasks. Take it one level higher and then you are writing <a href="http://www.cocoanetics.com/parts-store/">software components</a> that can be plugged into your own apps or even other people&#8217;s apps. Writing reusable code not only makes your life easier, it also forces you to think through and abstract interfaces such that your components are loosely coupled. That&#8217;s the essence of MVC (Model-View-Controller), the heart of Cocoa.</p>
<p>And some other activities that are only peripheral like blogging and podcasting. But I find that as long as you center it on a single topic then all your activities cross-pollinate. That&#8217;s why I gave up on Windows support or programming for any other platform than iOS. And I find that by writing about programming it forces me to chew through boring documentation and try out the techniques I&#8217;m covering. This META level of Cocoa Coding teaches me just as well as my readers.</p>
<p>Obviously it helps if you can do it full-time, that&#8217;s why I detailed this multi-prong strategy in my previous blog article <a href="http://www.cocoanetics.com/2010/01/business-as-unusual/">Business as Unusual</a>.</p>
<blockquote><p>2. Who made the shirt you were wearing in your <a href="http://www.youtube.com/watch?v=C5m9SnTxbo0">iPhone 4 unboxing video</a>?</p></blockquote>
<p>It was given to me last Christmas by my brother-in-law who has a friend who has the tools to make T-Shirts. Do you think I should start a line of Dr. Touch merchandising items? <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<blockquote><p>3. This might be going a little over-board, but do you mind taking a look at a few of my current iPhone &amp; iPad applications and tell me how I could improve them? I&#8217;d really appreciate it if you took the time to look over them and give me your diagnosis on how they can be improved or fixed up.</p></blockquote>
<p>I&#8217;m only judging what I see on the app store and those are just my first gut responses. If you have a minute to look at these apps too then please add your feedback in the comments.</p>
<p><a href="http://itunes.apple.com/at/app/uchat-for-iphone/id366365571?mt=8">uChat for iPhone</a> (FREE) / <a href="http://itunes.apple.com/at/app/uchat-for-ipad/id372118225?mt=8">uChat for iPad</a> ($0.99)</p>
<ul>
<li>make this into a hybrid app, drop the price to free and instead add iAds.</li>
<li>don&#8217;t have any screens that cover the entire display and only have 4 buttons</li>
<li>it looks to me that the chat screen only use half of the available area</li>
<li>Ramp up the design, now there is next to none, using the gray scroll view background makes the app look dead</li>
</ul>
<p><a href="http://itunes.apple.com/at/app/am-i-ugly/id358913358?mt=8">Am I Ugly</a> (FREE)</p>
<ul>
<li>there is no design, so the hard answer: Yes, you (the app) are ugly</li>
<li>apart from this it&#8217;s ok for a &#8220;Hello App Store&#8221; app, but to be something that you would want people to enjoy you&#8217;d have to make it way more useful.</li>
</ul>
<p><a href="http://itunes.apple.com/at/app/itweet/id357632437?mt=8">iTweet!</a> (FREE)</p>
<ul>
<li>there are half-baked attempts at design, but I don&#8217;t think you should mix gray round UI elements with standard blue nav bars</li>
<li>navigation controllers should always have a title for the nav bars to prevent user confusion</li>
<li>with iOS4 the need for the core functionality (tweet and listen to music simultaneously) is in doubt</li>
</ul>
<p><strong>Summary</strong></p>
<p>By the number of apps alone you are way ahead of me. It took me half a year part time work to get to 4 and I was 34 at that time. You have that number (and the attached experience) at half my age. So I won&#8217;t be surprised if you overtake me sooner or later.</p>
<p>You seem to be making good progress since I see you using not just clicked-together standard UI stuff, but you&#8217;re also using GameKit, interfacing Twitter API, TwitPi and other advanced techniques. This tells me that you have grown sufficient abstractive reasoning that you can take an API or framework and use it from your code.</p>
<p>Apple says that 60% of the work that flows into an app should be design and your apps are lacking in this regard. So either you should work on your app design skills by trying to paper-prototype apps similar to famous examples like Tapbots. Or you should hire a friend who has &#8220;an eye for such things&#8221; to help you lay out the UX (User Experience) and UI (User Interface).</p>
<p>Apart from this I can only recommend a daily work out regime. Collect Cocoa hours, 10k or more. Maybe that&#8217;s an idea for an app&#8230;</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2848&amp;md5=685a80e4ac934e684a6edb119ab6ac00" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/07/how-to-become-great-at-ios-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2848&amp;md5=685a80e4ac934e684a6edb119ab6ac00" type="text/html" />"
	</item>
		<item>
		<title>Drawing on UIImages</title>
		<link>http://www.cocoanetics.com/2010/07/drawing-on-uiimages/</link>
		<comments>http://www.cocoanetics.com/2010/07/drawing-on-uiimages/#comments</comments>
		<pubDate>Thu, 01 Jul 2010 15:49:46 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=2774</guid>
		<description><![CDATA[Jayesh asks: Thanks for your article on UIImage from UIView. Need one more favor; I am in situation where I want to draw line or area (e.g. rectangle) on UI Image (e.g. Blue print) and save it again. Basically I will show image and put circle / rectangle on image showing area in blue print and save it. How should I do that? Can you please suggest approach, sample codes etc? So the task is to take a UIImage, make it writable in some way and then make a new image out of that for later use. Off the top of my head, I can immediately think of two ways to do that: with UIKit and with CoreGraphics. CoreGraphics has a slight advantage, being lower level, of being thread-safe. But for a simple graphical addition to an existing image I see nothing wrong with UIKit. As usual you should only do very quick operations with UIKit because it requires to be run on the main thread which is the only thread updating the user interface. Label Buy an ad here Readability So, first, let&#8217;s create a method that adds a circle to a passed UIImage. - &#40;UIImage *&#41;imageByDrawingCircleOnImage:&#40;UIImage *&#41;image &#123; // begin a graphics context of sufficient size UIGraphicsBeginImageContext&#40;image.size&#41;; &#160; // draw original image into the context &#91;image drawAtPoint:CGPointZero&#93;; &#160; // get the context for CoreGraphics CGContextRef ctx = UIGraphicsGetCurrentContext&#40;&#41;; &#160; // set stroking color and draw circle &#91;&#91;UIColor redColor&#93; setStroke&#93;; &#160; // make circle rect 5 px from border CGRect circleRect = CGRectMake&#40;0, 0, image.size.width, image.size.height&#41;; circleRect = CGRectInset&#40;circleRect, 5, 5&#41;; &#160; // draw circle CGContextStrokeEllipseInRect&#40;ctx, circleRect&#41;; &#160; // make image out of bitmap context UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext&#40;&#41;; &#160; // free the context UIGraphicsEndImageContext&#40;&#41;; &#160; return retImage; &#125; This code is only using UIKit methods, except for the lonely CGContextStrokeEllipseInRect. This is the reason why we need to retrieve a handle for the current context. UIKit has it&#8217;s own reference so that all UI* methods work without specifically setting a context. Should you ever need to force a specific context that you had created elsewhere, then you can use UIGraphicsPushContext to put this other context &#8220;topmost&#8221; and UIGraphicsPopContext to clean up. To use the above mentioned function all you need is this: // load image from bundle UIImage *image = &#91;UIImage imageNamed:@&#34;user-1.png&#34;&#93;; &#160; // call circle drawing UIImage *imageWithCircle = &#91;self imageByDrawingCircleOnImage:image&#93;; &#160; // save it to documents NSString *documentsPath = &#91;NSSearchPathForDirectoriesInDomains&#40;NSDocumentDirectory, NSUserDomainMask, YES&#41; lastObject&#93;; NSString *filePath = &#91;documentsPath stringByAppendingPathComponent:@&#34;output.png&#34;&#93;; NSData *imageData = UIImagePNGRepresentation&#40;imageWithCircle&#41;; &#91;imageData writeToFile:filePath atomically:YES&#93;; &#160; NSLog&#40;@&#34;Saved new image to %@&#34;, filePath&#41;; So, that&#8217;s the UIKit variant. Sometimes though you need to draw on a background thread and thus have to be sure to use thread-safe methods. The iOS 4 release notes mention that drawing images and fonts is thread-safe as of SDK 4.0. Drawing to a graphics context in UIKit is now thread-safe. Specifically: The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads. String and image drawing is now thread-safe. Using color and font objects in multiple threads is now safe to do. So the above sample should be fine for most purposes. Calling it on a background thread would work on 4.0 and above, but cause weird error messages on earlier SDK versions. One example might be if you needed to draw contents of a CATiledLayer, which is occuring on a special background thread. So how would this example look in CoreGraphics and without UIKit functions? First we would require a method to create a bitmap context of sufficient size. I took an example I found somewhere and modified it to my needs. I actually discovered that you don&#8217;t have to allocate the storage for the bitmap context yourself, it works fine as of 3.2, even though the documentation states that you should not do that before 4.0. Well, it works, I&#8217;ll stick with it. CGContextRef newBitmapContextSuitableForSize&#40;CGSize size&#41; &#123; int pixelsWide = size.width; int pixelsHigh = size.height; CGContextRef context = NULL; CGColorSpaceRef colorSpace; // void * bitmapData; int bitmapByteCount; int bitmapBytesPerRow; &#160; bitmapBytesPerRow = &#40;pixelsWide * 4&#41;; //4 bitmapByteCount = &#40;bitmapBytesPerRow * pixelsHigh&#41;; &#160; /* bitmapData = malloc( bitmapByteCount ); &#160; memset(bitmapData, 0, bitmapByteCount); // set memory to black, alpha 0 &#160; if (bitmapData == NULL) { return NULL; } */ colorSpace = CGColorSpaceCreateDeviceRGB&#40;&#41;; &#160; context = CGBitmapContextCreate &#40; NULL, // instead of bitmapData pixelsWide, pixelsHigh, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedFirst&#41;; CGColorSpaceRelease&#40; colorSpace &#41;; &#160; if &#40;context== NULL&#41; &#123; // free (bitmapData); return NULL; &#125; &#160; return context; &#125; Note that if you would put the malloc back in then you also need to free the memory pointer after you&#8217;re done. Previously I did not know that so all this memory leaked. This approach of passing NULL instead of a pointer apparently [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/07/drawing-on-uiimages/"></g:plusone></div><p>Jayesh asks:</p>
<blockquote><p>Thanks for your article on UIImage from UIView.</p>
<p>Need one more favor; I am in situation where I want to draw line or area (e.g. rectangle) on UI Image (e.g. Blue print) and save it again.</p>
<p>Basically I will show image and put circle / rectangle on image showing area in blue print and save it.</p>
<p>How should I do that? Can you please suggest approach, sample codes etc?</p></blockquote>
<p>So the task is to take a UIImage, make it writable in some way and then make a new image out of that for later use. Off the top of my head, I can immediately think of two ways to do that: with UIKit and with CoreGraphics. CoreGraphics has a slight advantage, being lower level, of being thread-safe. But for a simple graphical addition to an existing image I see nothing wrong with UIKit. As usual you should only do very quick operations with UIKit because it requires to be run on the main thread which is the only thread updating the user interface.</p>
<p><span id="more-2774"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>So, first, let&#8217;s create a method that adds a circle to a passed UIImage.</p>

<div class="wp_codebox"><table><tr id="p277453"><td class="code" id="p2774code53"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>imageByDrawingCircleOnImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// begin a graphics context of sufficient size</span>
	UIGraphicsBeginImageContext<span style="color: #002200;">&#40;</span>image.size<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// draw original image into the context</span>
	<span style="color: #002200;">&#91;</span>image drawAtPoint<span style="color: #002200;">:</span>CGPointZero<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// get the context for CoreGraphics</span>
	CGContextRef ctx <span style="color: #002200;">=</span> UIGraphicsGetCurrentContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// set stroking color and draw circle</span>
	<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor redColor<span style="color: #002200;">&#93;</span> setStroke<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// make circle rect 5 px from border</span>
	CGRect circleRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>,
				image.size.width,
				image.size.height<span style="color: #002200;">&#41;</span>;
	circleRect <span style="color: #002200;">=</span> CGRectInset<span style="color: #002200;">&#40;</span>circleRect, <span style="color: #2400d9;">5</span>, <span style="color: #2400d9;">5</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// draw circle</span>
	CGContextStrokeEllipseInRect<span style="color: #002200;">&#40;</span>ctx, circleRect<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// make image out of bitmap context</span>
	UIImage <span style="color: #002200;">*</span>retImage <span style="color: #002200;">=</span> UIGraphicsGetImageFromCurrentImageContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// free the context</span>
	UIGraphicsEndImageContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> retImage;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This code is only using UIKit methods, except for the lonely CGContextStrokeEllipseInRect. This is the reason why we need to retrieve a handle for the current context. UIKit has it&#8217;s own reference so that all UI* methods work without specifically setting a context. Should you ever need to force a specific context that you had created elsewhere, then you can use UIGraphicsPushContext to put this other context &#8220;topmost&#8221; and UIGraphicsPopContext to clean up.</p>
<p>To use the above mentioned function all you need is this:</p>

<div class="wp_codebox"><table><tr id="p277454"><td class="code" id="p2774code54"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// load image from bundle</span>
UIImage <span style="color: #002200;">*</span>image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;user-1.png&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// call circle drawing</span>
UIImage <span style="color: #002200;">*</span>imageWithCircle <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self imageByDrawingCircleOnImage<span style="color: #002200;">:</span>image<span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// save it to documents</span>
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>documentsPath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>NSSearchPathForDirectoriesInDomains<span style="color: #002200;">&#40;</span>NSDocumentDirectory,
							NSUserDomainMask, <span style="color: #a61390;">YES</span><span style="color: #002200;">&#41;</span> lastObject<span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/"><span style="color: #400080;">NSString</span></a> <span style="color: #002200;">*</span>filePath <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>documentsPath stringByAppendingPathComponent<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;output.png&quot;</span><span style="color: #002200;">&#93;</span>;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/"><span style="color: #400080;">NSData</span></a> <span style="color: #002200;">*</span>imageData <span style="color: #002200;">=</span> UIImagePNGRepresentation<span style="color: #002200;">&#40;</span>imageWithCircle<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#91;</span>imageData writeToFile<span style="color: #002200;">:</span>filePath atomically<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Saved new image to %@&quot;</span>, filePath<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>So, that&#8217;s the UIKit variant. Sometimes though you need to draw on a background thread and thus have to be sure to use thread-safe methods.</p>
<p>The <a href="http://developer.apple.com/iphone/library/releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html">iOS 4 release notes</a> mention that drawing images and fonts is thread-safe as of SDK 4.0.</p>
<blockquote><p>Drawing to a graphics context in UIKit is now thread-safe. Specifically:</p>
<ul>
<li>The routines used to access and manipulate the graphics context can now correctly handle contexts residing on different threads.</li>
<li>String and image drawing is now thread-safe.</li>
</ul>
<p>Using color and font objects in multiple threads is now safe to do.</p></blockquote>
<p>So the above sample should be fine for most purposes. Calling it on a background thread would work on 4.0 and above, but cause weird error messages on earlier SDK versions. One example might be if you needed to draw contents of a CATiledLayer, which is occuring on a special background thread.</p>
<p>So how would this example look in CoreGraphics and without UIKit functions?</p>
<p>First we would require a method to create a bitmap context of sufficient size. I took an example I found somewhere and modified it to my needs. I actually discovered that you don&#8217;t have to allocate the storage for the bitmap context yourself, it works fine as of 3.2, even though the documentation states that you should not do that before 4.0. Well, it works, I&#8217;ll stick with it.</p>

<div class="wp_codebox"><table><tr id="p277455"><td class="code" id="p2774code55"><pre class="objc" style="font-family:monospace;">CGContextRef newBitmapContextSuitableForSize<span style="color: #002200;">&#40;</span>CGSize size<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">int</span> pixelsWide <span style="color: #002200;">=</span> size.width;
	<span style="color: #a61390;">int</span> pixelsHigh <span style="color: #002200;">=</span> size.height;
    CGContextRef    context <span style="color: #002200;">=</span> <span style="color: #a61390;">NULL</span>;
    CGColorSpaceRef colorSpace;
   <span style="color: #11740a; font-style: italic;">// void *          bitmapData;</span>
    <span style="color: #a61390;">int</span>             bitmapByteCount;
    <span style="color: #a61390;">int</span>             bitmapBytesPerRow;
&nbsp;
    bitmapBytesPerRow   <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>pixelsWide <span style="color: #002200;">*</span> <span style="color: #2400d9;">4</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">//4</span>
    bitmapByteCount     <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span>bitmapBytesPerRow <span style="color: #002200;">*</span> pixelsHigh<span style="color: #002200;">&#41;</span>;
&nbsp;
   <span style="color: #11740a; font-style: italic;">/* bitmapData = malloc( bitmapByteCount );
&nbsp;
	memset(bitmapData, 0, bitmapByteCount);  // set memory to black, alpha 0
&nbsp;
    if (bitmapData == NULL)
    {
        return NULL;
    }
*/</span>
	colorSpace <span style="color: #002200;">=</span> CGColorSpaceCreateDeviceRGB<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	context <span style="color: #002200;">=</span> CGBitmapContextCreate <span style="color: #002200;">&#40;</span> <span style="color: #a61390;">NULL</span>, <span style="color: #11740a; font-style: italic;">// instead of bitmapData</span>
					pixelsWide,
					pixelsHigh,
					<span style="color: #2400d9;">8</span>,      <span style="color: #11740a; font-style: italic;">// bits per component</span>
					bitmapBytesPerRow,
					colorSpace,
					kCGImageAlphaPremultipliedFirst<span style="color: #002200;">&#41;</span>;
	CGColorSpaceRelease<span style="color: #002200;">&#40;</span> colorSpace <span style="color: #002200;">&#41;</span>;
&nbsp;
    <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>context<span style="color: #002200;">==</span> <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span>
    <span style="color: #002200;">&#123;</span>
       <span style="color: #11740a; font-style: italic;">// free (bitmapData);</span>
        <span style="color: #a61390;">return</span> <span style="color: #a61390;">NULL</span>;
    <span style="color: #002200;">&#125;</span>
&nbsp;
    <span style="color: #a61390;">return</span> context;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that if you would put the malloc back in then you also need to free the memory pointer after you&#8217;re done. Previously I did not know that so all this memory leaked. This approach of passing NULL instead of a pointer apparently works on 3.2 and above, officially from 4.0.</p>

<div class="wp_codebox"><table><tr id="p277456"><td class="code" id="p2774code56"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>imageByDrawingCircleOnImageCG<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
<span style="color: #002200;">&#123;</span>
	<span style="color: #11740a; font-style: italic;">// begin a graphics context of sufficient size</span>
	CGContextRef ctx <span style="color: #002200;">=</span> newBitmapContextSuitableForSize<span style="color: #002200;">&#40;</span>image.size<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// need to flip the transform matrix</span>
	<span style="color: #11740a; font-style: italic;">// CoreGraphics has (0,0) in lower left</span>
	CGContextScaleCTM<span style="color: #002200;">&#40;</span>ctx, <span style="color: #2400d9;">1</span>, <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
	CGContextTranslateCTM<span style="color: #002200;">&#40;</span>ctx, <span style="color: #2400d9;">0</span>, <span style="color: #002200;">-</span>image.size.height<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// draw original image into the context</span>
	CGRect imageRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>, image.size.width, image.size.height<span style="color: #002200;">&#41;</span>;
	CGContextDrawImage<span style="color: #002200;">&#40;</span>ctx, imageRect, image.CGImage<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// set stroking color and draw circle</span>
	CGContextSetRGBStrokeColor<span style="color: #002200;">&#40;</span>ctx, <span style="color: #2400d9;">1</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// make circle rect 5 px from border</span>
	CGRect circleRect <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>,
			image.size.width,
			image.size.height<span style="color: #002200;">&#41;</span>;
	circleRect <span style="color: #002200;">=</span> CGRectInset<span style="color: #002200;">&#40;</span>circleRect, <span style="color: #2400d9;">5</span>, <span style="color: #2400d9;">5</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// draw circle</span>
	CGContextStrokeEllipseInRect<span style="color: #002200;">&#40;</span>ctx, circleRect<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// make image out of bitmap context</span>
	CGImageRef cgImage <span style="color: #002200;">=</span> CGBitmapContextCreateImage<span style="color: #002200;">&#40;</span>ctx<span style="color: #002200;">&#41;</span>;
	UIImage <span style="color: #002200;">*</span>retImage <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageWithCGImage<span style="color: #002200;">:</span>cgImage<span style="color: #002200;">&#93;</span>;
	CGImageRelease<span style="color: #002200;">&#40;</span>cgImage<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// free the context</span>
	CGContextRelease<span style="color: #002200;">&#40;</span>ctx<span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> retImage;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Besides of having to use this helper function to create a suitable bitmap context you should also note that we have to go via creating a CGImage first. From this we can then create a UIImage. Also you might have spotted that we need to turn the transformation matrix upside down because otherwise all our graphics would be that. CoreGraphics generally assumes the origin of drawing in the lower left hand corner.</p>
<p>I&#8217;ve shown you both methods of drawing on images, now you can take your pick which one you prefer.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2774&amp;md5=a8530cf0f97f5ba40c8bd03f46621ec7" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/07/drawing-on-uiimages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2774&amp;md5=a8530cf0f97f5ba40c8bd03f46621ec7" type="text/html" />"
	</item>
		<item>
		<title>Service Announcement: Upgrading iOS 4 GM</title>
		<link>http://www.cocoanetics.com/2010/06/service-announcement-upgrading-ios-4-gm/</link>
		<comments>http://www.cocoanetics.com/2010/06/service-announcement-upgrading-ios-4-gm/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 15:16:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=2749</guid>
		<description><![CDATA[A not-to-be-named friend asked me: I would like your opinion the GM build. Should I (not sure how) remove it and then load the new iOS 4.0? I know it wouldn&#8217;t have the game center, but I don&#8217;t use that anyway. I am afraid if I don&#8217;t remove, the software will expire (happened on beta 4 and then I couldn&#8217;t use the phone (or back up first) until I could load the latest. If you&#8217;re one of those developers that managed to install the iOS 4.0 Gold Master right after Uncle Steve announced it, then you might wonder if you should update to the really final release that came out just now. Wait! That&#8217;s a trick question&#8230;! Label Buy an ad here Readability A version is called Gold Master if it is the final code that would be put on a master CD to be mass-produced by the factory. Since we are getting iOS updates via the Internet there is no longer any physical media involved. A different name, less anachronistic, would have been RTM (&#8220;Release to Manufacturing&#8221;). Or not, there is no manufacturing involved in unleashing Apple software upon the world. So let&#8217;s see if that really WAS true and we got the really REALLY finaly 4.0 version after the Stevenote. To check on which version is the latest I used a trick I learned from TUAW to get a list of the ipsw restore files bearing version 4.0. They employed the OSX built-in text-to-speech engine to have the Mac tell you as soon as the 4.0 version became available on Apple&#8217;s servers. A cool trick! But we need only the first line of their script: curl -s -L http://phobos.apple.com/version &#124; grep -i Restore &#124; grep -i iPhone &#124; grep -i 4.0 This part gets an XML file from Apple&#8217;s servers and cuts out the lines that include iPhone, Restore and 4.0. You get several lines that all share the same build number: 8A293. Now let&#8217;s cross check that against our own phone, that we have already be-goldened. Down there at Version it also says 8A293. Heureka! Apple told the truth when they told us that we developers will get the final shipping version of iOS 4.0. Check for yourself if you have this build number. If yes, then you might see if you can fool somebody else and ask them if they already upgraded to the really final 4.0.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/06/service-announcement-upgrading-ios-4-gm/"></g:plusone></div><p>A not-to-be-named friend asked me:</p>
<blockquote><p>I would like your opinion the GM build. Should I (not sure how) remove it and then load the new iOS 4.0? I know it wouldn&#8217;t have the game center, but I don&#8217;t use that anyway. I am afraid if I don&#8217;t remove, the software will expire (happened on beta 4 and then I couldn&#8217;t use the phone (or back up first) until I could load the latest.</p></blockquote>
<p>If you&#8217;re one of those developers that managed to install the iOS 4.0 Gold Master right after Uncle Steve announced it, then you might wonder if you should update to the really final release that came out just now.</p>
<p><em>Wait! That&#8217;s a trick question&#8230;!</em></p>
<p><span id="more-2749"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>A version is called <a href="http://en.wikipedia.org/wiki/Golden_master">Gold Master</a> if it is the final code that would be put on a master CD to be mass-produced by the factory. Since we are getting iOS updates via the Internet there is no longer any physical media involved. A different name, less anachronistic, would have been RTM (&#8220;Release to Manufacturing&#8221;). Or not, there is no manufacturing involved in unleashing Apple software upon the world.</p>
<p>So let&#8217;s see if that really WAS true and we got the really REALLY finaly 4.0 version after the Stevenote. To check on which version is the latest I used a trick I learned from TUAW to get a list of the ipsw restore files bearing version 4.0. They employed the OSX built-in text-to-speech engine to have the Mac <a href="http://www.tuaw.com/2010/06/21/ios-4-0-firmware-release-expected-momentarily-quick-terminal-ti/">tell you as soon as the 4.0 version became available</a> on Apple&#8217;s servers. A cool trick! But we need only the first line of their script:</p>

<div class="wp_codebox"><table><tr id="p274958"><td class="code" id="p2749code58"><pre class="objc" style="font-family:monospace;">curl <span style="color: #002200;">-</span>s <span style="color: #002200;">-</span>L http<span style="color: #002200;">:</span><span style="color: #11740a; font-style: italic;">//phobos.apple.com/version | grep -i Restore | grep -i iPhone | grep -i 4.0</span></pre></td></tr></table></div>

<p>This part gets an XML file from Apple&#8217;s servers and cuts out the lines that include iPhone, Restore and 4.0. You get several lines that all share the same build number: <strong>8A293</strong>.</p>
<p>Now let&#8217;s cross check that against our own phone, that we have already be-goldened.</p>
<p><a href="http://www.cocoanetics.com/files/IMG_0002.png"><img class="alignnone size-full wp-image-2750" src="http://www.cocoanetics.com/files/IMG_0002.png" alt="" width="320" height="480" /></a></p>
<p>Down there at Version it also says 8A293. Heureka! Apple told the truth when they told us that we developers will get the final shipping version of iOS 4.0.</p>
<p>Check for yourself if you have this build number. If yes, then you might see if you can fool somebody else and ask them if they already upgraded to the really final 4.0. <img src='http://www.cocoanetics.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2749&amp;md5=214ad57948d81fd110ff62f4d1a40c4f" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/06/service-announcement-upgrading-ios-4-gm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2749&amp;md5=214ad57948d81fd110ff62f4d1a40c4f" type="text/html" />"
	</item>
		<item>
		<title>Timing is Everything</title>
		<link>http://www.cocoanetics.com/2010/03/timing-is-everything/</link>
		<comments>http://www.cocoanetics.com/2010/03/timing-is-everything/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 08:03:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=2295</guid>
		<description><![CDATA[zeke817 asks: Hey guys just wondering how to put a timer in the appdelegate. I need a timer to keep playing on through multiple views instead of just playing on 1 view. Any help apperciated Using timers is pretty simple. There are plenty examples around and it&#8217;s not difficult to understand. Having said that, I am responding to this question for three reasons: my posts on my blog have been pretty scarce recently due to lots of programming for customer projects I think I should at least document how I am using timers so that I can refer people to this post when the question arises again and again. Explaining a simple thing to somebody else is the best way to train clarity in teaching. Generally speaking timers are not instantiated but scheduled. The difference is that the SDK/OS takes care of their memory management and we only have to worry about whether or not we want them to fire. So we don&#8217;t need to ever release a timer, instead we invalidate it. Label Buy an ad here Readability Now your choice is to have a timer fire just once or repeatedly. If you want it ongoing then it&#8217;s wise to have an instance variable defined in the header for saving the address of the NSTimer instance in so that we can command it to invalidate itself once we no longer want it to go on. It it&#8217;s just a one-off thing, then we don&#8217;t need an IVAR. That means adding this to the header&#8217;s interface description between the curly brackets, a variable named &#8220;timer&#8221; which points (asterisk) to an NSTimer instance. NSTimer *myTimer; Somewhere in our code we want to start the timer. There are two methods of creating a timer, via invocation or target/selector. The second one is easier to understand so it&#8217;s the one I&#8217;ve been using. With it you specify the method that you want to be called back on every time the timer fires. myTimer = &#91;NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector&#40;timerFired:&#41; userInfo:nil repeats:YES&#93;; That creates a timer, that will fire after 5 seconds and then repeatedly every 5 seconds. When it fires it will call timerFired: in the same instance you scheduled it, due to using self. You could also be passing some user data, but we don&#8217;t need that for now, so we pass nil. Of course we need to provide the timerFired: method as well: - &#40;void&#41; timerFired:&#40;NSTimer *&#41;timer &#123; NSLog&#40;@&#34;Tick&#34;&#41;; &#125; If you have an ongoing timer the least you should do is to invalidate it in the class dealloc. If you are invalidating it without destroying the instance you should also set your instance variable to nil because invalidating an already invalidated timer causes an exception. But [nil invalidate] is always ignored by objective-C. - &#40;void&#41;dealloc &#123; &#91;myTimer invalidate&#93;, myTimer = nil; // other releases &#91;super dealloc&#93;; &#125; Having a pointer to the timer allows you to do a couple of useful things with the instance methods that NSTimer provides. You can fire it manually, you can ask it if it isValid or you can invalidate it. Because internally NSTimer works with dates (more precisely: with a time duration in seconds since a reference date) for when it fires and not durations you can also get fireDate or setFireDate. Now about userInfo, you can put anything in there that you like to have present as data in the timerFired method. If you&#8217;re just scheduling timer events for self, then this is mostly useless as you can access all instance variables anyway. But if you have some calculated data from right before the scheduling that&#8217;s not in an IVAR then you can pass it. Or if you are scheduling the receiver of the timerEvent to be a different object then it has much more usefulness. Timers are a great invention, especially for achieving repeated calling of a given method. Though when you find yourself creating timers with repeats:NO then you might be better of using performSelector:withObject:afterDelay:, I think this is cleaner especially since another developer usually expects timers to be continuous.]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/03/timing-is-everything/"></g:plusone></div><p>zeke817 asks:</p>
<blockquote><p>Hey guys just wondering how to put a timer in the appdelegate. I need a timer to keep playing on through multiple views instead of just playing on 1 view. Any help apperciated</p></blockquote>
<p>Using timers is pretty simple. There are plenty examples around and it&#8217;s not difficult to understand. Having said that, I am responding to this question for three reasons:</p>
<ol>
<li>my posts on my blog have been pretty scarce recently due to lots of programming for customer projects</li>
<li>I think I should at least document how I am using timers so that I can refer people to this post when the question arises again and again.</li>
<li>Explaining a simple thing to somebody else is the best way to train clarity in teaching.</li>
</ol>
<p>Generally speaking timers are not instantiated but <em>scheduled</em>. The difference is that the SDK/OS takes care of their memory management and we only have to worry about whether or not we want them to fire. So we don&#8217;t need to ever release a timer, instead we <em>invalidate</em> it.</p>
<p><span id="more-2295"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Now your choice is to have a timer fire just once or repeatedly. If you want it ongoing then it&#8217;s wise to have an instance variable defined in the header for saving the address of the NSTimer instance in so that we can command it to invalidate itself once we no longer want it to go on. It it&#8217;s just a one-off thing, then we don&#8217;t need an IVAR.</p>
<p>That means adding this to the header&#8217;s interface description between the curly brackets, a variable named &#8220;timer&#8221; which points (asterisk) to an NSTimer instance.</p>

<div class="wp_codebox"><table><tr id="p229563"><td class="code" id="p2295code63"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/"><span style="color: #400080;">NSTimer</span></a> <span style="color: #002200;">*</span>myTimer;</pre></td></tr></table></div>

<p>Somewhere in our code we want to start the timer. There are two methods of creating a timer, via invocation or target/selector. The second one is easier to understand so it&#8217;s the one I&#8217;ve been using. With it you specify the method that you want to be called back on every time the timer fires.</p>

<div class="wp_codebox"><table><tr id="p229564"><td class="code" id="p2295code64"><pre class="objc" style="font-family:monospace;">myTimer <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/"><span style="color: #400080;">NSTimer</span></a> scheduledTimerWithTimeInterval<span style="color: #002200;">:</span><span style="color: #2400d9;">5.0</span> target<span style="color: #002200;">:</span>self
                               selector<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>timerFired<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span> userInfo<span style="color: #002200;">:</span><span style="color: #a61390;">nil</span> repeats<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>That creates a timer, that will fire after 5 seconds and then repeatedly every 5 seconds. When it fires it will call timerFired: in the same instance you scheduled it, due to using self. You could also be passing some user data, but we don&#8217;t need that for now, so we pass nil.</p>
<p>Of course we need to provide the timerFired: method as well:</p>

<div class="wp_codebox"><table><tr id="p229565"><td class="code" id="p2295code65"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> timerFired<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/"><span style="color: #400080;">NSTimer</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>timer
<span style="color: #002200;">&#123;</span>
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Tick&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>If you have an ongoing timer the least you should do is to invalidate it in the class dealloc. If you are invalidating it without destroying the instance you should also set your instance variable to nil because invalidating an already invalidated timer causes an exception. But [nil invalidate] is always ignored by objective-C.</p>

<div class="wp_codebox"><table><tr id="p229566"><td class="code" id="p2295code66"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>dealloc
<span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>myTimer invalidate<span style="color: #002200;">&#93;</span>, myTimer <span style="color: #002200;">=</span> <span style="color: #a61390;">nil</span>;
    <span style="color: #11740a; font-style: italic;">// other releases</span>
    <span style="color: #002200;">&#91;</span>super dealloc<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Having a pointer to the timer allows you to do a couple of useful things with the instance methods that NSTimer provides. You can <em>fire</em> it manually, you can ask it if it <em>isValid</em> or you can <em>invalidate</em> it. Because internally NSTimer works with dates (more precisely: with a time duration in seconds since a reference date) for when it fires and not durations you can also get <em>fireDate</em> or <em>setFireDate</em>.</p>
<p>Now about userInfo, you can put anything in there that you like to have present as data in the timerFired method. If you&#8217;re just scheduling timer events for self, then this is mostly useless as you can access all instance variables anyway. But if you have some calculated data from right before the scheduling that&#8217;s not in an IVAR then you can pass it. Or if you are scheduling the receiver of the timerEvent to be a different object then it has much more usefulness.</p>
<p>Timers are a great invention, especially for achieving repeated calling of a given method. Though when you find yourself creating timers with repeats:NO then you might be better of using performSelector:withObject:afterDelay:, I think this is cleaner especially since another developer usually expects timers to be continuous.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2295&amp;md5=674de34422deaac1e3889bc2d0134a29" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/03/timing-is-everything/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2295&amp;md5=674de34422deaac1e3889bc2d0134a29" type="text/html" />"
	</item>
		<item>
		<title>“Are You a Cocoa Crack?” Quiz (2)</title>
		<link>http://www.cocoanetics.com/2010/02/are-you-a-cocoa-crack-quiz-2/</link>
		<comments>http://www.cocoanetics.com/2010/02/are-you-a-cocoa-crack-quiz-2/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 14:14:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=1866</guid>
		<description><![CDATA[It&#8217;s been more than half a year since I published the first installment of this Quiz aimed at Cocoa Cracks. Back then people seemed to like the challenges I presented. So I collected a few more nuggets. If you ever stumbled on an crash or strange result that you did not expect, then mail it to me. These questions will show if you are really the Cocoa Crack you like to believe to be. To see the answer highlight the answer text with your mouse. No peeking! Respond in the comments how many you got correct. Quiz: Warm Up. Your UI designer gave you a PNG with the instruction &#8220;just tile this in the background&#8221; of a UIView. Do you have to subclass UIView, overriding the drawRect of the view and performing drawImage for all tiles? Or is there a simpler method? Answer: You create a UIImage by loading the PNG and then create a &#8220;color&#8221; from it with [UIColor colorWithPatternImage:image]. Then you apply this as the background color of the view. Quiz: Suddenly your app crashes and when the debugger opens it first loads lots of stack frames. All you did is override a property like shown below. What&#8217;s the bug? Bonus Question: where&#8217;s the memory leak? - &#40;void&#41; setTextColor:&#40;UIColor *&#41;newTextColor &#123; if &#40;newTextColor != textColor&#41; &#123; &#91;textColor release&#93;; &#160; if &#40;newTextColor&#41; &#123; self.textColor = &#91;newTextColor retain&#93;; &#125; else // default &#123; self.textColor = &#91;&#91;UIColor whiteColor&#93; retain&#93;; &#125; bubbleView.highlightedTextColor = textColor; &#125; &#125; Answer: You have an endless recursion. self.textColor is a simplified way to write [self setTextColor:]. So this method keeps calling itself until the stack is full and your app gets terminated. The leak is calling retain on an assignment to a retaining property. But if you fix the crashing bug by removing both self then there is no leak. Quiz: You want to draw two lines in a drawRect, a horizontal black line and a white line 1 pixel below it. So you write the following code. But instead of the intended result you get this picture in magnification, the black is dark gray and the white is a lighter shade of gray. Why is that and how would you fix it? CGContextRef currentContext = UIGraphicsGetCurrentContext&#40;&#41;; &#160; // Draw a black line at the top and a white line 1 pixel below &#160; CGContextSetLineWidth&#40;currentContext, 1&#41;; &#160; CGContextSetRGBStrokeColor&#40;currentContext, 0.0, 0.0, 0.0, 1.0&#41;; // Black CGContextMoveToPoint&#40;currentContext, 0, 0&#41;; // top left CGContextAddLineToPoint&#40;currentContext, rect.size.width, 0&#41;; // to top right CGContextStrokePath&#40;currentContext&#41;; &#160; CGContextSetRGBStrokeColor&#40;currentContext, 1.0, 1.0, 1.0, 1.0&#41;; // White CGContextMoveToPoint&#40;currentContext, 0, 1&#41;; // left CGContextAddLineToPoint&#40;currentContext, rect.size.width, 1&#41;; CGContextStrokePath&#40;currentContext&#41;; Answer: Core Graphics does not work on pixels directly, that&#8217;s why you use floating point numbers for coordinates. It works on coordinates and the resulting bitmap is always rendered. Half of the line width is always applied half a unit to each side of the line. To remedy this you need to move the coordinates of the lines by half a unit up or down. (Thanks to Michael Kaye for sending this in) Quiz: You have a UITableView and would like for it to have rounded corners. What&#8217;s the fastest way to achieve that? Which header is necessary? Answer: You can have any UIView have rounded corners by setting the cornerRadius property of it&#8217;s CALayer. The layer of a UIView is actually what&#8217;s responsible for drawing the contents of the view. You need: to import &#60;QuartzCore/QuartzCore.h&#62; Quiz: You have created a UIViewController which shows a UIWebView and has a navigation bar. You want to set the title on the bar to be the same as the title of the HTML document once loading has finished. Would you need to parse the HTML with NSScanner to find the &#60;title&#62; tag and extract it? Or is there a simpler method? Answer: In the webViewDidFinishLoad: delegate method you retrieve the title via javascript and set it like that. self.title = [webView stringByEvaluatingJavaScriptFromString: @"document.title"]; Quiz: You have written code to load some UIImages in the background (performSelectorOnBackgroundThread or NSInvocationOperation). The loading code calls the method below to resize the loaded image. This has &#8220;always working before&#8221;, but suddenly you keep getting a EXC_BAD_ACESS on the line marked. You have double checked all retains and even set NSZombieEnabled to YES because usually you get this message if you are using an overreleased object. But that did not fix the problem. What&#8217;s the reason for the crash and how would you fix it? + &#40;UIImage*&#41;imageWithImage:&#40;UIImage*&#41;image scaledToSize:&#40;CGSize&#41;newSize; &#123; UIGraphicsBeginImageContext&#40; newSize &#41;; &#91;image drawInRect:CGRectMake&#40;0,0,newSize.width,newSize.height&#41;&#93;; // &#38;lt;- crash UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext&#40;&#41;; UIGraphicsEndImageContext&#40;&#41;; &#160; return newImage; &#125; Answer: UIKit is not thread-safe. Therefore all drawing via UIKit needs to happen on the main thread. The UIGraphicsBeginImageContext works to create the context, but the memory for it is owned to the main thread and trying to access it with drawInRect from another thread [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/02/are-you-a-cocoa-crack-quiz-2/"></g:plusone></div><p>It&#8217;s been more than half a year since I published the <a href="http://www.cocoanetics.com/2009/07/cocoa-crack-quiz-1/">first installment</a> of this Quiz aimed at Cocoa Cracks. Back then people seemed to like the challenges I presented. So I collected a few more nuggets. If you ever stumbled on an crash or strange result that you did not expect, then mail it to me.</p>
<p>These questions will show if you are really the Cocoa Crack you like to believe to be. To see the answer highlight the answer text with your mouse. No peeking! Respond in the comments how many you got correct.</p>
<p><strong>Quiz:</strong> Warm Up. Your UI designer gave you a PNG with the instruction &#8220;just tile this in the background&#8221; of a UIView. Do you have to subclass UIView, overriding the drawRect of the view and performing drawImage for all tiles? Or is there a simpler method?</p>
<p><strong>Answer:</strong> <span style="color: #fbfbfb">You create a UIImage by loading the PNG and then create a &#8220;color&#8221; from it with [UIColor colorWithPatternImage:image]. Then you apply this as the background color of the view.<br />
</span></p>
<hr /><strong>Quiz:</strong> Suddenly your app crashes and when the debugger opens it first loads lots of stack frames. All you did is override a property like shown below. What&#8217;s the bug? Bonus Question: where&#8217;s the memory leak?</p>

<div class="wp_codebox"><table><tr id="p186670"><td class="code" id="p1866code70"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> setTextColor<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIColor <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>newTextColor
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>newTextColor <span style="color: #002200;">!=</span> textColor<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#91;</span>textColor release<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>newTextColor<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			self.textColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>newTextColor retain<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#125;</span>
		<span style="color: #a61390;">else</span> <span style="color: #11740a; font-style: italic;">// default</span>
		<span style="color: #002200;">&#123;</span>
			self.textColor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIColor whiteColor<span style="color: #002200;">&#93;</span> retain<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#125;</span>
		bubbleView.highlightedTextColor <span style="color: #002200;">=</span> textColor;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p><strong>Answer:</strong> <span style="color: #fbfbfb">You have an endless recursion. self.textColor is a simplified way to write [self setTextColor:]. So this method keeps calling itself until the stack is full and your app gets terminated. The leak is calling retain on an assignment to a retaining property. But if you fix the crashing bug by removing both self then there is no leak.</span></p>
<hr /><strong>Quiz: </strong>You want to draw two lines in a drawRect, a horizontal black line and a white line 1 pixel below it. So you write the following code. But instead of the intended result you get this picture in magnification, the black is dark gray and the white is a lighter shade of gray. Why is that and how would you fix it?</p>
<p><a href="http://www.cocoanetics.com/files/Picture-4.png"><img class="alignnone size-full wp-image-1868" src="http://www.cocoanetics.com/files/Picture-4.png" alt="" width="205" height="8" /></a></p>

<div class="wp_codebox"><table><tr id="p186671"><td class="code" id="p1866code71"><pre class="objc" style="font-family:monospace;">CGContextRef currentContext <span style="color: #002200;">=</span> UIGraphicsGetCurrentContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// Draw a black line at the top and a white line 1 pixel below</span>
&nbsp;
CGContextSetLineWidth<span style="color: #002200;">&#40;</span>currentContext, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
&nbsp;
CGContextSetRGBStrokeColor<span style="color: #002200;">&#40;</span>currentContext, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">0.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// Black</span>
CGContextMoveToPoint<span style="color: #002200;">&#40;</span>currentContext, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// top left</span>
CGContextAddLineToPoint<span style="color: #002200;">&#40;</span>currentContext, rect.size.width, <span style="color: #2400d9;">0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// to top right</span>
CGContextStrokePath<span style="color: #002200;">&#40;</span>currentContext<span style="color: #002200;">&#41;</span>;
&nbsp;
CGContextSetRGBStrokeColor<span style="color: #002200;">&#40;</span>currentContext, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// White</span>
CGContextMoveToPoint<span style="color: #002200;">&#40;</span>currentContext, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>; <span style="color: #11740a; font-style: italic;">// left</span>
CGContextAddLineToPoint<span style="color: #002200;">&#40;</span>currentContext, rect.size.width, <span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>;
CGContextStrokePath<span style="color: #002200;">&#40;</span>currentContext<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p><strong>Answer:</strong> <span style="color: #fbfbfb">Core Graphics does not work on pixels directly, that&#8217;s why you use floating point numbers for coordinates. It works on coordinates and the resulting bitmap is always rendered. Half of the line width is always applied half a unit to each side of the line. To remedy this you need to move the coordinates of the lines by half a unit up or down.</span></p>
<p>(Thanks to <a href="http://www.sendmetospace.co.uk/">Michael Kaye</a> for sending this in)</p>
<hr /><strong>Quiz: </strong>You have a UITableView and would like for it to have rounded corners. What&#8217;s the fastest way to achieve that? Which header is necessary?</p>
<p><strong>Answer:</strong> <span style="color: #fbfbfb">You can have any UIView have rounded corners by setting the cornerRadius property of it&#8217;s CALayer. The layer of a UIView is actually what&#8217;s responsible for drawing the contents of the view. You need: to import  &lt;QuartzCore/QuartzCore.h&gt;</span></p>
<hr /><strong>Quiz: </strong>You have created a UIViewController which shows a UIWebView and has a navigation bar. You want to set the title on the bar to be the same as the  title of the HTML document once loading has finished. Would you need to parse the HTML with NSScanner to find the &lt;title&gt; tag and extract it? Or is there a simpler method?</p>
<p><strong>Answer:</strong> <span style="color: #fbfbfb">In the webViewDidFinishLoad: delegate method you retrieve the title via javascript and set it like that. self.title = [webView stringByEvaluatingJavaScriptFromString: @"document.title"];<br />
</span></p>
<hr />
<p><strong>Quiz: </strong>You have written code to load some UIImages in the background (performSelectorOnBackgroundThread or NSInvocationOperation). The loading code calls the method below to resize the loaded image. This has &#8220;always working before&#8221;, but suddenly you keep getting a EXC_BAD_ACESS on the line marked. You have double checked all retains and even set NSZombieEnabled to YES because usually you get this message if you are using an overreleased object. But that did not fix the problem. What&#8217;s the reason for the crash and how would you fix it?</p>

<div class="wp_codebox"><table><tr id="p186672"><td class="code" id="p1866code72"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>imageWithImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage<span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image
			  scaledToSize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGSize<span style="color: #002200;">&#41;</span>newSize;
<span style="color: #002200;">&#123;</span>
	UIGraphicsBeginImageContext<span style="color: #002200;">&#40;</span> newSize <span style="color: #002200;">&#41;</span>;
	<span style="color: #002200;">&#91;</span>image drawInRect<span style="color: #002200;">:</span>CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>,<span style="color: #2400d9;">0</span>,newSize.width,newSize.height<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;   <span style="color: #11740a; font-style: italic;">// &amp;lt;- crash</span>
	UIImage<span style="color: #002200;">*</span> newImage <span style="color: #002200;">=</span> UIGraphicsGetImageFromCurrentImageContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
	UIGraphicsEndImageContext<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #a61390;">return</span> newImage;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p><strong>Answer:</strong> <span style="color: #fbfbfb">UIKit is not thread-safe. Therefore all drawing via UIKit needs to happen on the main thread. The UIGraphicsBeginImageContext works to create the context, but the memory for it is owned to the main thread and trying to access it with drawInRect from another thread is causing this exception. To fix it you need to rewrite this method to create your own bitmap context on the non-main thread so that you then own the memory for it. After creating the bitmap context you draw the image to it with CGContextDrawImage and then create a new CGImage with CGBitmapContextCreateImage. From the CGImage you create a UIImage to return from the method.</span></p>
<hr />
<p><strong>Quiz: </strong>Off the top of your head: how many methods do you know of having a piece of code contained in one method being performed in the background? Which?</p>
<p><strong>Answer:</strong> <span style="color: #fbfbfb">Correct Answers are: performSelectorOnBackgroundThread and creating an NSInvocationOperation from the selector as those work on an existing method. Creating an NSOperation sub-class or manual threading with NSThread are also valid answers, but those require that you move the code into a new class or need to be well versed with threading voodoo.<br />
</span></p>
<hr />
<p>So how many answers did you know? Be honest! If you also have a Cocoa riddle like these to contribute please mail them directly to me (oliver@drobnik.com) and I will publish them in this format.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=1866&amp;md5=5a08eb91d5d328f342c647e3b2b5465e" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/02/are-you-a-cocoa-crack-quiz-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=1866&amp;md5=5a08eb91d5d328f342c647e3b2b5465e" type="text/html" />"
	</item>
		<item>
		<title>UIImageView + Touch Handling = UIButton</title>
		<link>http://www.cocoanetics.com/2010/02/uiimageview-touch-handling-uibutton/</link>
		<comments>http://www.cocoanetics.com/2010/02/uiimageview-touch-handling-uibutton/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 10:34:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.drobnik.com/touch/?p=2054</guid>
		<description><![CDATA[gdscei asks: &#8220;Hello, how can i make an image view work as a button? I want it to be assigned to the &#8216;reload&#8217; action of WebView. Can someone give me instructions how to do this?&#8221; Often people start out constructing their UI visually, starting with this line of reasoning &#8220;I want to show an image. Ah, UIImageView&#8221;. So they create the visual appearance of their UI either by clicking it together in Interface Builder or &#8211; if slightly more advanced in their coding skills &#8211; creating those image views in code. So if we create a new view-based project in XCode, we could modify the viewDidLoad of the main view controller like this to show the image: - &#40;void&#41;viewDidLoad &#123; &#91;super viewDidLoad&#93;; &#160; UIImageView *imageView = &#91;&#91;UIImageView alloc&#93; initWithFrame: CGRectMake&#40;100.0, 100.0, 57.0, 57.0&#41;&#93;; imageView.image = &#91;UIImage imageNamed:@&#34;Icon.png&#34;&#93;; &#91;self.view addSubview:imageView&#93;; &#91;imageView release&#93;; &#125; The next logical step in reasoning right after displaying the icon is now to get touch handling somehow. And that&#8217;s where you will get stuck because UIImageView is a dead end when it comes to reacting to the user&#8217;s finger. Label Buy an ad here Readability Sure, if you consider yourself extra smart and that you won&#8217;t be stumped by such an inconvenient &#8220;cul de sac&#8221; then you will proceed to subclass UIImageView and adding touch handling via the touchesBegan, touchesMoved, touchesCancelled and touchesEnded method. And don&#8217;t go telling me that you would never make such a mistake. I know, I did and I&#8217;ve seen smarter programmers than the both of us proceed to painstakingly code their own touch handling for UIImageViews. This post is NOT about doing that. I cannot prevent you from scratching your left ear with your right index finger, but I CAN show a smarter way to get your own interactive custom buttons. I already gave away half of the solution: CUSTOM BUTTONS. Apple made it confusing to beginners by having the default style for a button being a rounded rectangle with text inside. That&#8217;s why there is such a strong trend to using UIImageViews because beginners cannot imagine that their beautifully crafted button images would fit into this rounded container. But in fact the rounded rectangle style is only one of several possibilities. UIButtonType can have these values: UIButtonTypeCustom, UIButtonTypeRoundedRect UIButtonTypeDetailDisclosure UIButtonTypeInfoLight UIButtonTypeInfoDark UIButtonTypeContactAdd The very first on UIButtonTypeCustom will be our choice for making our own custom button. For all the other button types Apple provides the drawing, for the custom one you have to bring your own, preferably in the form of UIImages for the various states. Let&#8217;s have a brief look at the inheritance of UIImageView versus UIButton. This kinship was not obvious to me, I only discovered it by accident when I also was in the situation that I wanted to touch-enable some subviews. UIImageView inherits from UIView : UIResponder : NSObject UIButton inherits from UIControl : UIView : UIResponder : NSObject So we can see that up to UIView both have the same set of methods and behaviors. An image view is just a UIView where an image from a property is being drawn in the view&#8217;s area, probably inside the drawRect. A button gains an additional level of inheritance: UIControl. If you read up on UIControl in the documentation it tells you that UIControl adds mechanisms to &#8220;convey user intent to the application&#8221;. It adds the target-action methodology to UIView where you can add targets and methods as actions that get executed when certain things happen. Like for example a touch is lifted inside a button or the value of a slider has changed. But UIImageView and UIButton are views! Both have the genes of UIView inside of them and cannot deny their pedigree. Knowing the above mentioned facts, why would you want to painstakingly code your own touch handling routines if you get them for free when choosing UIButton to display your icon image instead? We can replace the above mentioned code with this: - &#40;void&#41;viewDidLoad &#123; &#91;super viewDidLoad&#93;; &#160; UIButton *imageButton = &#91;UIButton buttonWithType:UIButtonTypeCustom&#93;; imageButton.frame = CGRectMake&#40;100.0, 100.0, 57.0, 57.0&#41;; &#91;imageButton setImage:&#91;UIImage imageNamed:@&#34;Icon.png&#34;&#93; forState:UIControlStateNormal&#93;; &#91;self.view addSubview:imageButton&#93;; &#125; Note that for buttons you generally don&#8217;t do alloc-initWithFrame, but use the factory method buttonWithType. Since this gives us an autoreleased button we don&#8217;t need to manually release it after addSubview. If you do that you get exactly the same result, with a minor difference. If you tap the icon it darkens automatically to show the touch. That&#8217;s because UIButton expects to display something different when the button is touched. You can set a specific image for the highlighted state, if you don&#8217;t then UIButton takes the normal state image and darkens it automatically. To disable this behavior change the property or set an image for the highlighted state: imageButton.adjustsImageWhenHighlighted = NO; // or &#91;imageButton setImage:&#91;UIImage imageNamed:@&#34;Icon_highlighted.png&#34;&#93; forState:UIControlStateHighlighted&#93;; [...]]]></description>
			<content:encoded><![CDATA[<div class="plus-one-wrap"><g:plusone href="http://www.cocoanetics.com/2010/02/uiimageview-touch-handling-uibutton/"></g:plusone></div><p>gdscei asks:</p>
<blockquote><p>&#8220;Hello, how can i make an image view work as a button? I want it to be assigned to the &#8216;reload&#8217; action of WebView.<br />
Can someone give me instructions how to do this?&#8221;</p></blockquote>
<p>Often people start out constructing their UI visually, starting with this line of reasoning &#8220;I want to show an image. Ah, UIImageView&#8221;. So they create the visual appearance of their UI either by clicking it together in Interface Builder or &#8211; if slightly more advanced in their coding skills &#8211; creating those image views in code.</p>
<p>So if we create a new view-based project in XCode, we could modify the viewDidLoad of the main view controller like this to show the image:</p>

<div class="wp_codebox"><table><tr id="p205479"><td class="code" id="p2054code79"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
	UIImageView <span style="color: #002200;">*</span>imageView <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>UIImageView alloc<span style="color: #002200;">&#93;</span> initWithFrame<span style="color: #002200;">:</span>
		CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">100.0</span>, <span style="color: #2400d9;">100.0</span>, <span style="color: #2400d9;">57.0</span>, <span style="color: #2400d9;">57.0</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
	imageView.image <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Icon.png&quot;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>self.view addSubview<span style="color: #002200;">:</span>imageView<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>imageView release<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The next logical step in reasoning right after displaying the icon is now to get touch handling somehow. And that&#8217;s where you will get stuck because UIImageView is a dead end when it comes to reacting to the user&#8217;s finger.</p>
<p><span id="more-2054"></span></p>
<div class="inner_ad_block">
<div id="advman-7" class="widget Advman_Widget">
<h3 class="widgettitle"></h3>
<p><!-- BuySellAds.com Zone Code --></p>
<div id="bsap_1260346" class="bsarocks bsap_fc3166ea4a479e0fdb4251fbe92a1219"></div>
<p><!-- End BuySellAds.com Zone Code --></div>
<div id="text-21" class="widget widget_text">
<h3 class="widgettitle">Label</h3>
<div class="textwidget">
<div class="advert-notice"><a href="http://buysellads.com/buy/detail/56639/zone/1260346">Buy an ad here</a></div>
</div></div>
<div id="text-14" class="widget widget_text">
<h3 class="widgettitle">Readability</h3>
<div class="textwidget">
<div id='rdbWrapper'></div>
<p><script type='text/javascript'>
(function() {
    var s     = document.getElementsByTagName('script')[0],
        rdb   = document.createElement('script');
    rdb.type  = 'text/javascript';
    rdb.async = true;
    rdb.src   = document.location.protocol + '//www.readability.com/embed.js';
    s.parentNode.insertBefore(rdb, s);
})();
</script></div>
</p></div>
</div>
<p>Sure, if you consider yourself extra smart and that you won&#8217;t be stumped by such an inconvenient &#8220;cul de sac&#8221; then you will proceed to subclass UIImageView and adding touch handling via the touchesBegan, touchesMoved, touchesCancelled and touchesEnded method. And don&#8217;t go telling me that you would never make such a mistake. I know, I did and I&#8217;ve seen smarter programmers than the both of us proceed to painstakingly code their own touch handling for UIImageViews.</p>
<p>This post is NOT about doing that. I cannot prevent you from scratching your left ear with your right index finger, but I CAN show a smarter way to get your own interactive custom buttons.</p>
<p>I already gave away half of the solution: CUSTOM BUTTONS. Apple made it confusing to beginners by having the default style for a button being a rounded rectangle with text inside. That&#8217;s why there is such a strong trend to using UIImageViews because beginners cannot imagine that their beautifully crafted button images would fit into this rounded container. But in fact the rounded rectangle style is only one of several possibilities.</p>
<p>UIButtonType can have these values:</p>
<ul>
<li>UIButtonTypeCustom,</li>
<li>UIButtonTypeRoundedRect</li>
<li>UIButtonTypeDetailDisclosure</li>
<li>UIButtonTypeInfoLight</li>
<li>UIButtonTypeInfoDark</li>
<li>UIButtonTypeContactAdd</li>
</ul>
<p>The very first on UIButtonTypeCustom will be our choice for making our own custom button. For all the other button types Apple provides the drawing, for the custom one you have to bring your own, preferably in the form of UIImages for the various states.</p>
<p>Let&#8217;s have a brief look at the inheritance of UIImageView versus UIButton. This kinship was not obvious to me, I only discovered it by accident when I also was in the situation that I wanted to touch-enable some subviews.</p>
<p>UIImageView inherits from UIView : UIResponder : NSObject<br />
UIButton inherits from UIControl : UIView : UIResponder : NSObject</p>
<p>So we can see that up to UIView both have the same set of methods and behaviors. An image view is just a UIView where an image from a property is being drawn in the view&#8217;s area, probably inside the drawRect. A button gains an additional level of inheritance: UIControl. If you read up on UIControl in the documentation it tells you that UIControl adds mechanisms to &#8220;convey user intent to the application&#8221;. It adds the target-action methodology to UIView where you can add targets and methods as actions that get executed when certain things happen. Like for example a touch is lifted inside a button or the value of a slider has changed.</p>
<p>But UIImageView and UIButton are views! Both have the genes of UIView inside of them and cannot deny their pedigree.</p>
<p>Knowing the above mentioned facts, why would you want to painstakingly code your own touch handling routines if you get them for free when choosing UIButton to display your icon image instead?</p>
<p>We can replace the above mentioned code with this:</p>

<div class="wp_codebox"><table><tr id="p205480"><td class="code" id="p2054code80"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span>viewDidLoad <span style="color: #002200;">&#123;</span>
    <span style="color: #002200;">&#91;</span>super viewDidLoad<span style="color: #002200;">&#93;</span>;
&nbsp;
    UIButton <span style="color: #002200;">*</span>imageButton <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>UIButton buttonWithType<span style="color: #002200;">:</span>UIButtonTypeCustom<span style="color: #002200;">&#93;</span>;
    imageButton.frame <span style="color: #002200;">=</span> CGRectMake<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">100.0</span>, <span style="color: #2400d9;">100.0</span>, <span style="color: #2400d9;">57.0</span>, <span style="color: #2400d9;">57.0</span><span style="color: #002200;">&#41;</span>;
    <span style="color: #002200;">&#91;</span>imageButton setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Icon.png&quot;</span><span style="color: #002200;">&#93;</span> forState<span style="color: #002200;">:</span>UIControlStateNormal<span style="color: #002200;">&#93;</span>;
    <span style="color: #002200;">&#91;</span>self.view addSubview<span style="color: #002200;">:</span>imageButton<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that for buttons you generally don&#8217;t do alloc-initWithFrame, but use the factory method buttonWithType. Since this gives us an autoreleased button we don&#8217;t need to manually release it after addSubview.</p>
<p>If you do that you get exactly the same result, with a minor difference. If you tap the icon it darkens automatically to show the touch. That&#8217;s because UIButton expects to display something different when the button is touched. You can set a specific image for the highlighted state, if you don&#8217;t then UIButton takes the normal state image and darkens it automatically.</p>
<p>To disable this behavior change the property or set an image for the highlighted state:</p>

<div class="wp_codebox"><table><tr id="p205481"><td class="code" id="p2054code81"><pre class="objc" style="font-family:monospace;">imageButton.adjustsImageWhenHighlighted <span style="color: #002200;">=</span> <span style="color: #a61390;">NO</span>;
<span style="color: #11740a; font-style: italic;">// or</span>
<span style="color: #002200;">&#91;</span>imageButton setImage<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>UIImage imageNamed<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Icon_highlighted.png&quot;</span><span style="color: #002200;">&#93;</span>
	forState<span style="color: #002200;">:</span>UIControlStateHighlighted<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>Possible control states are:</p>

<div class="wp_codebox"><table><tr id="p205482"><td class="code" id="p2054code82"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">enum</span> <span style="color: #002200;">&#123;</span>
   UIControlStateNormal               <span style="color: #002200;">=</span> <span style="color: #2400d9;">0</span>,
   UIControlStateHighlighted          <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">0</span>,
   UIControlStateDisabled             <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">1</span>,
   UIControlStateSelected             <span style="color: #002200;">=</span> <span style="color: #2400d9;">1</span> &lt;&lt; <span style="color: #2400d9;">2</span>,
   UIControlStateApplication          <span style="color: #002200;">=</span> 0x00FF0000,
   UIControlStateReserved             <span style="color: #002200;">=</span> 0xFF000000
<span style="color: #002200;">&#125;</span>;</pre></td></tr></table></div>

<p>Therefore control state is more than a single value, it actually can also be a combination of several bits. The normal state is 0, the highlighted state is 1, disabled 2 and selected 4. You can specify any combination thereof by using the bitwise or operator |. For example to set an image for selected OR highlighted you use UIControlStateSelected|UIControlStateHighlighted. This possibility is not clear if you look at the inspector for a button in Interface Builder. That&#8217;s why I prefer to do my buttons in code.</p>
<p>To clarify the states: A button at rest is &#8220;normal&#8221;. As long as you put your finger down on it, it&#8217;s &#8220;highlighted&#8221;. If you lift again, it returns to &#8220;normal&#8221;. If you set it&#8217;s enabled property to NO, then it&#8217;s &#8220;disabled&#8221;. If you set it&#8217;s selected property to YES, then it&#8217;s &#8220;selected&#8221;.</p>
<p>Cocoa Cracks NOTE that UIControlStateApplication actually shows us a range (16 bits) that we can use ourselves to define extra special states for our own controls. And UIControlStateReserved is a range (16 bits) that is reserved for Apple-internal use.</p>
<p>Ok, so much for states and looks. Adding targets and actions for the various possible interactions with a button is easy again:</p>

<div class="wp_codebox"><table><tr id="p205483"><td class="code" id="p2054code83"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span>imageButton addTarget<span style="color: #002200;">:</span>self action<span style="color: #002200;">:</span><span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>buttonPushed<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span>
	  forControlEvents<span style="color: #002200;">:</span>UIControlEventTouchUpInside<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>We also have to implement the &#8220;action&#8221; which is just a method. The target is the class instance where you implement the method, the action is a selector, i.e. the &#8220;fingerprint&#8221; of the method.</p>

<div class="wp_codebox"><table><tr id="p205484"><td class="code" id="p2054code84"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">void</span><span style="color: #002200;">&#41;</span> buttonPushed<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>sender
<span style="color: #002200;">&#123;</span>
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;It works!&quot;</span><span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Note that a pointer to your button instance will be passed via the sender parameter. This can sometimes be useful, for example if you want to use a single method to respond to multiple buttons. In this case you would use the tag of the passed sender to discern which button the call was coming from.</p>
<p>This method of making images respond to touches works with very little extra tying. I&#8217;m using it in <a href="http://www.cocoanetics.com/2010/02/dtcalendarviewcontroller-2-0/">DTCalendarView</a> for the individual days as well as for a full screen tap recognition in <a href="http://www.cocoanetics.com/2010/02/dtsplashextender/">DTSplashExtender</a>. Best of all: it saves you lot of extra code or even having to subclass UIImageView.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2054&amp;md5=3895cd6a121695796081643c836ee573" title="Flattr" target="_blank"><img src="http://www.cocoanetics.com/wp-content/plugins/flattr/img/flattr-badge-large.png" alt="flattr this!"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.cocoanetics.com/2010/02/uiimageview-touch-handling-uibutton/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<atom:link rel="payment" href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=2054&amp;md5=3895cd6a121695796081643c836ee573" type="text/html" />"
	</item>
	</channel>
</rss>

