<?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>Sat, 18 May 2013 06:19:23 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
	<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F&amp;language=en_US&amp;category=text&amp;title=Cocoanetics&amp;description=Our+DNA+is+written+in+Objective-C&amp;tags=blog" type="text/html" />
		<item>
		<title>DTCoreText: Centering an Image</title>
		<link>http://www.cocoanetics.com/2013/04/dtcoretext-centering-an-image/</link>
		<comments>http://www.cocoanetics.com/2013/04/dtcoretext-centering-an-image/#comments</comments>
		<pubDate>Sun, 07 Apr 2013 13:09:18 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7991</guid>
		<description><![CDATA[Amy Worall asks: How do I centre an image in DTCoreText? I’m working with attributed strings not HTML. Any sample code? In this blog post will answer this. DTCoreText consists of multiple parts: tools for converting between HTML and attributed strings, a custom layout engine doing the &#8220;frame setting&#8221; and (on iOS) several UI classes for displaying those attributed strings. For most scenarios you would want to simply pass in some HTML data and display that, but Amy&#8217;s use case seems to forego this step. And there is nothing wrong with skipping directly to putting together an NSAttributedString. As long as you use the same attributes that the HTML parser would put in there the result should be identical. Amy is trying to get a divider image centered amongst the text. This should be a simple exercise, but somehow it comes out as being off center. Looking at the sample code she provided didn&#8217;t yield any clues as to what could be reason for this. My first thought when seeing this was that this has to be a bug in DTCoreText. Feelings of Panic starting to rise. Try it in the Demo App So my search for the cause of the off-centering began with the DTCoreText demo app. I like to make sure I have the latest version of DTCoreText (and submodules) cloned and then I try to find a place where I can test the text. If I have HTML that does not seem to come out right, then I paste it into the CurrentTest.html which is the last menu option in the demo&#8217;s menu of snippets. So the first test I am doing is to see if maybe centered paragraphs are broken somehow. In HTML you can switch to centered paragraph styles with the &#60;center&#62; tag or with the equivalent CSS text-align attribute. Images that are contained in the app bundle can be referenced without any path. &#60;html&#62; &#60;head&#62; &#60;body&#62; &#60;center&#62;&#60;img src="Oliver.jpg" width="100" height="100"&#62;&#60;/center&#62; &#60;p&#62; Lorem ipsum dolor sit amet, ... &#60;/p&#62; &#60;/body&#62; &#60;/html&#62; Push the &#8220;Debug Frames&#8221; button to have DTCoreText draw additional backgrounds behind the glyph runs, the frame outline. There is also a dashed centering line. &#160; We can see that the image is centered on the centering line. At least we know that the problem must lie elsewhere. Inspecting the Chars view shows that the image paragraph consists of the Unicode Object Placeholder @&#8221;\ufffc&#8221; character and a newline (code 10). The Ranges view shows that the placholder character has a DTTextAttachment attribute, a run delegate attribute as well as a paragraph style with alignment 2 for centering. The placeholder character is not being displayed itself. Instead CoreText calls the run delegate to get the dimensions from the text attachment. The run delegate asks the DTTextAttachment for Ascent, Descent and Width to be reserved so that the image has enough space to fit. Since the run delegate is a set of C-functions it has no context from being in the scope of an object. For this purpose there is a context parameter in which we pass a pointer to the text attachment. The text attachment object and the run delegate always exist retained by the same attribute range this is possible, even under ARC. And Now in Code Amy provided the following gist of the code she&#8217;s been experimenting with. With what I explained above, can you spot the problem? NSMutableParagraphStyle *centredPS = &#91;&#91;NSMutableParagraphStyle alloc&#93; init&#93;; centredPS.alignment = NSTextAlignmentCenter; &#160; NSMutableAttributedString *attributedStringBuilder = &#91;NSMutableAttributedString new&#93;; &#160; DTTextAttachment *attachment = &#91;&#91;DTTextAttachment alloc&#93; init&#93;; UIImage *image = &#91;UIImage imageNamed:@&#34;divider&#34;&#93;; attachment.contents = image; attachment.contentType = DTTextAttachmentTypeImage; attachment.displaySize = image.size; NSMutableDictionary *newAttributes = &#91;NSMutableDictionary new&#93;; &#91;newAttributes setObject:attachment forKey:NSAttachmentAttributeName&#93;; &#91;newAttributes setObject:centredPS forKey:NSParagraphStyleAttributeName&#93;; &#91;attributedStringBuilder appendAttributedString:&#91;&#91;NSAttributedString alloc&#93; initWithString:UNICODE_OBJECT_PLACEHOLDER attributes:newAttributes&#93;&#93;; &#160; &#91;attributedStringBuilder appendString:@&#34;\n&#34;&#93;; &#160; // then append all our normal paragraphs of text. // This is eventually given to a DTAttributedTextView to display. And no, I&#8217;m not referring to Amy spelling &#8220;center&#8221; incorrectly throughout. The run delegate is missing. If I paste this code into DemoAboutViewController, reducing the attachment display size to 100&#215;100. This comes out quite weird. Apparently this spaces the lines correctly from the top (done in DTCoreTextLayoutFrame), but the ascender of the image (the part going up from the base line) is only as high as the font&#8217;s ascender. This explains why in Amy&#8217;s sample image the divider looks like it is vertically in the correct position. It has a height similar to the font height. Let&#8217;s add in the missing run delegate. // need run delegate for sizing CTRunDelegateRef embeddedObjectRunDelegate = createEmbeddedObjectRunDelegate&#40;&#40;id&#41;attachment&#41;; &#91;newAttributes setObject:&#40;__bridge id&#41;embeddedObjectRunDelegate forKey:&#40;id&#41;kCTRunDelegateAttributeName&#93;; CFRelease&#40;embeddedObjectRunDelegate&#41;; Build&#38;Run and we can marvel at the correct placement of my face. Pretty, eh? (I mean the positioning) To simplify things I have this category on NSAttributedString in DTRichTextEditor for inserting images into the editable text. + &#40;NSAttributedString *&#41;attributedStringWithImage:&#40;UIImage *&#41;image maxDisplaySize:&#40;CGSize&#41;maxDisplaySize &#123; DTTextAttachment *attachment [...]]]></description>
				<content:encoded><![CDATA[<p>Amy Worall asks:</p>
<blockquote><p>How do I centre an image in DTCoreText? I’m working with attributed strings not HTML. Any sample code?</p></blockquote>
<p>In this blog post will answer this.</p>
<p><span id="more-7991"></span></p>
<div id="more-7991"></div>
<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>
<p>DTCoreText consists of multiple parts: tools for converting between HTML and attributed strings, a custom layout engine doing the &#8220;frame setting&#8221; and (on iOS) several UI classes for displaying those attributed strings.</p>
<p>For most scenarios you would want to simply pass in some HTML data and display that, but Amy&#8217;s use case seems to forego this step. And there is nothing wrong with skipping directly to putting together an NSAttributedString. As long as you use the same attributes that the HTML parser would put in there the result should be identical.</p>
<p>Amy is trying to get a divider image centered amongst the text. This should be a simple exercise, but somehow it comes out as being off center. Looking at the sample code she provided didn&#8217;t yield any clues as to what could be reason for this.</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/BG7rJiaCMAE8GUy.png-large.png"><img class="alignnone size-full wp-image-7992" alt="BG7rJiaCMAE8GUy.png-large" src="http://i1.wp.com/www.cocoanetics.com/files/BG7rJiaCMAE8GUy.png-large.png?resize=640%2C288" data-recalc-dims="1" /></a></p>
<p>My first thought when seeing this was that this has to be a bug in <strong>DTCoreText</strong>. Feelings of Panic starting to rise.</p>
<h3>Try it in the Demo App</h3>
<p>So my search for the cause of the off-centering began with the DTCoreText demo app. I like to make sure I have the latest version of DTCoreText (and submodules) cloned and then I try to find a place where I can test the text.</p>
<p>If I have HTML that does not seem to come out right, then I paste it into the CurrentTest.html which is the last menu option in the demo&#8217;s menu of snippets.</p>
<p>So the first test I am doing is to see if maybe centered paragraphs are broken somehow. In HTML you can switch to centered paragraph styles with the &lt;center&gt; tag or with the equivalent CSS text-align attribute. Images that are contained in the app bundle can be referenced without any path.</p>
<pre>&lt;html&gt;
&lt;head&gt;
&lt;body&gt;
&lt;center&gt;&lt;img src="Oliver.jpg" width="100" height="100"&gt;&lt;/center&gt;
&lt;p&gt;
Lorem ipsum dolor sit amet, ...
&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Push the &#8220;Debug Frames&#8221; button to have DTCoreText draw additional backgrounds behind the glyph runs, the frame outline. There is also a dashed centering line.</p>
<p><a href="http://i2.wp.com/www.cocoanetics.com/files/iOS-Simulator-Screen-shot-Apr-7-2013-2.10.22-PM.png"><img class="alignnone size-full wp-image-7993" alt="iOS Simulator Screen shot Apr 7, 2013 2.10.22 PM" src="http://i2.wp.com/www.cocoanetics.com/files/iOS-Simulator-Screen-shot-Apr-7-2013-2.10.22-PM.png?resize=640%2C960" data-recalc-dims="1" /></a></p>
<p>&nbsp;</p>
<p>We can see that the image is centered on the centering line. At least we know that the problem must lie elsewhere.</p>
<p>Inspecting the <strong>Chars</strong> view shows that the image paragraph consists of the Unicode Object Placeholder @&#8221;\ufffc&#8221; character and a newline (code 10). The <strong>Ranges</strong> view shows that the placholder character has a DTTextAttachment attribute, a run delegate attribute as well as a paragraph style with alignment 2 for centering.</p>
<p>The placeholder character is not being displayed itself. Instead CoreText calls the run delegate to get the dimensions from the text attachment. The run delegate asks the DTTextAttachment for Ascent, Descent and Width to be reserved so that the image has enough space to fit. Since the run delegate is a set of C-functions it has no context from being in the scope of an object. For this purpose there is a context parameter in which we pass a pointer to the text attachment.</p>
<p>The text attachment object and the run delegate always exist retained by the same attribute range this is possible, even under ARC.</p>
<h3>And Now in Code</h3>
<p>Amy provided the following gist of the code she&#8217;s been experimenting with. With what I explained above, can you spot the problem?</p>

<div class="wp_codebox"><table><tr id="p79914"><td class="code" id="p7991code4"><pre class="objc" style="font-family:monospace;"><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSMutableParagraphStyle_Class/"><span style="color: #400080;">NSMutableParagraphStyle</span></a> <span style="color: #002200;">*</span>centredPS <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/ApplicationKit/Classes/NSMutableParagraphStyle_Class/"><span style="color: #400080;">NSMutableParagraphStyle</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
centredPS.alignment <span style="color: #002200;">=</span> NSTextAlignmentCenter;
&nbsp;
<a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/"><span style="color: #400080;">NSMutableAttributedString</span></a> <span style="color: #002200;">*</span>attributedStringBuilder <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/"><span style="color: #400080;">NSMutableAttributedString</span></a> new<span style="color: #002200;">&#93;</span>;
&nbsp;
DTTextAttachment <span style="color: #002200;">*</span>attachment <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTTextAttachment alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</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;divider&quot;</span><span style="color: #002200;">&#93;</span>;
attachment.contents <span style="color: #002200;">=</span> image;
attachment.contentType <span style="color: #002200;">=</span> DTTextAttachmentTypeImage;
attachment.displaySize <span style="color: #002200;">=</span> image.size;
<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>newAttributes <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> new<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>newAttributes setObject<span style="color: #002200;">:</span>attachment forKey<span style="color: #002200;">:</span>NSAttachmentAttributeName<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>newAttributes setObject<span style="color: #002200;">:</span>centredPS forKey<span style="color: #002200;">:</span>NSParagraphStyleAttributeName<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>attributedStringBuilder appendAttributedString<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/NSAttributedString_Class/"><span style="color: #400080;">NSAttributedString</span></a> alloc<span style="color: #002200;">&#93;</span> 
                         initWithString<span style="color: #002200;">:</span>UNICODE_OBJECT_PLACEHOLDER attributes<span style="color: #002200;">:</span>newAttributes<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #002200;">&#91;</span>attributedStringBuilder appendString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;<span style="color: #2400d9;">\n</span>&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// then append all our normal paragraphs of text.</span>
<span style="color: #11740a; font-style: italic;">// This is eventually given to a DTAttributedTextView to display.</span></pre></td></tr></table></div>

<p>And no, I&#8217;m not referring to Amy spelling &#8220;center&#8221; incorrectly throughout. <img src='http://i1.wp.com/www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' data-recalc-dims="1" /> </p>
<p>The run delegate is missing.</p>
<p>If I paste this code into DemoAboutViewController, reducing the attachment display size to 100&#215;100. This comes out quite weird.</p>
<p><a href="http://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-04-07-at-2.38.20-PM.png"><img class="alignnone size-full wp-image-7994" alt="Screen Shot 2013-04-07 at 2.38.20 PM" src="http://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-04-07-at-2.38.20-PM.png?resize=320%2C209" data-recalc-dims="1" /></a></p>
<p>Apparently this spaces the lines correctly from the top (done in DTCoreTextLayoutFrame), but the ascender of the image (the part going up from the base line) is only as high as the font&#8217;s ascender. This explains why in Amy&#8217;s sample image the divider looks like it is vertically in the correct position. It has a height similar to the font height.</p>
<p>Let&#8217;s add in the missing run delegate.</p>

<div class="wp_codebox"><table><tr id="p79915"><td class="code" id="p7991code5"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// need run delegate for sizing</span>
CTRunDelegateRef embeddedObjectRunDelegate <span style="color: #002200;">=</span> createEmbeddedObjectRunDelegate<span style="color: #002200;">&#40;</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>attachment<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#91;</span>newAttributes setObject<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>__bridge <span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>embeddedObjectRunDelegate forKey<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>kCTRunDelegateAttributeName<span style="color: #002200;">&#93;</span>;
CFRelease<span style="color: #002200;">&#40;</span>embeddedObjectRunDelegate<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>Build&amp;Run and we can marvel at the correct placement of my face.</p>
<p><a href="http://i0.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-04-07-at-2.45.24-PM.png"><img class="alignnone size-large wp-image-7996" alt="Screen Shot 2013-04-07 at 2.45.24 PM" src="http://i0.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-04-07-at-2.45.24-PM.png?resize=318%2C207" data-recalc-dims="1" /></a></p>
<p><em>Pretty, eh? </em>(I mean the positioning)</p>
<p>To simplify things I have this category on NSAttributedString in <a href="http://www.cocoanetics.com/parts/dtrichtexteditor/">DTRichTextEditor</a> for inserting images into the editable text.</p>

<div class="wp_codebox"><table><tr id="p79916"><td class="code" id="p7991code6"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">+</span> <span style="color: #002200;">&#40;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSAttributedString_Class/"><span style="color: #400080;">NSAttributedString</span></a> <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>attributedStringWithImage<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>UIImage <span style="color: #002200;">*</span><span style="color: #002200;">&#41;</span>image maxDisplaySize<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span>CGSize<span style="color: #002200;">&#41;</span>maxDisplaySize
<span style="color: #002200;">&#123;</span>
   DTTextAttachment <span style="color: #002200;">*</span>attachment <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTTextAttachment alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
   attachment.contents <span style="color: #002200;">=</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span><span style="color: #002200;">&#41;</span>image;
   attachment.originalSize <span style="color: #002200;">=</span> image.size;
   attachment.contentType <span style="color: #002200;">=</span> DTTextAttachmentTypeImage;
&nbsp;
   CGSize displaySize <span style="color: #002200;">=</span> image.size;
   <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>CGSizeEqualToSize<span style="color: #002200;">&#40;</span>maxDisplaySize, CGSizeZero<span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
   <span style="color: #002200;">&#123;</span>
      <span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>maxDisplaySize.width &lt; image.size.width || 
          maxDisplaySize.height &lt; image.size.height<span style="color: #002200;">&#41;</span>
      <span style="color: #002200;">&#123;</span>
         displaySize <span style="color: #002200;">=</span> sizeThatFitsKeepingAspectRatio<span style="color: #002200;">&#40;</span>image.size,maxDisplaySize<span style="color: #002200;">&#41;</span>;
      <span style="color: #002200;">&#125;</span>
   <span style="color: #002200;">&#125;</span>
   attachment.displaySize <span style="color: #002200;">=</span> displaySize;
&nbsp;
   DTHTMLElement <span style="color: #002200;">*</span>element <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTHTMLElement alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
   element.textAttachment <span style="color: #002200;">=</span> attachment;
&nbsp;
   <span style="color: #a61390;">return</span> <span style="color: #002200;">&#91;</span>element attributedString<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This constructs the attributed string with the image exactly like DTCoreText does, via DTHTMLElement. There you can find that the run delegate is being added if the attachment property is not nil. This also adjusts the display size to fit a given maximum display size unless you pass CGSizeZero for that.</p>
<h3>Conclusion</h3>
<p>In DTCoreText (on iOS) besides a DTTextAttachment we need to also specify a run delegate so that Core Text is able to reserve the appropriate space for it. On Mac attributed strings can have attachments as well. There they are embedded in NSTextAttachment instances which have a file wrapper for the file as well as a cell for sizing and displaying the content. </p>
<p>Apple has brought over NSTextAttachment in iOS 6, but kept it private API. This is why I came up with this workaround using the killer combo of Run Delegate + DTTextAttachment. This is compatible all the way down to iOS 4.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7991&amp;md5=ab792656f0d97cb31a4f54b3f5f2ece2" 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/2013/04/dtcoretext-centering-an-image/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2013%2F04%2Fdtcoretext-centering-an-image%2F&amp;language=en_GB&amp;category=text&amp;title=DTCoreText%3A+Centering+an+Image&amp;description=Amy+Worall+asks%3A+How+do+I+centre+an+image+in+DTCoreText%3F+I%E2%80%99m+working+with+attributed+strings+not+HTML.+Any+sample+code%3F+In+this+blog+post+will+answer+this.+DTCoreText+consists...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Using Custom Fonts with DTCoreText</title>
		<link>http://www.cocoanetics.com/2013/03/using-custom-fonts-with-dtcoretext/</link>
		<comments>http://www.cocoanetics.com/2013/03/using-custom-fonts-with-dtcoretext/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 14:36:48 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7854</guid>
		<description><![CDATA[Friend of DTCoreText Holger was having problems getting DTCoreText to use the bold font face of his custom font. I want to take this opportunity to explain what the root cause for Holger&#8217;s problem was and what you need to know if you&#8217;re using custom fonts with DTCoreText. DTCoreText has access to all the fonts that are installed on the iOS device, as well as those that you bundle with your app. Fonts are always grouped by Font Family. The individual looks are called Font Faces. Typically you will have 4 variants there: regular, bold, italic and bold+italic. Apple&#8217;s Core Text system supports TrueType (TTF) as well as OpenType (OTF) fonts. Bundle the Font After copying the font files into your app, you assigning them to the target so that they get copied together with the other app resources. You have to register the font file names in your app&#8217;s info.plist so that they get loaded on app launch. The font files go into the &#8220;Fonts provided by application&#8221; section, aka UIAppFonts. To check if the fonts get loaded correctly you can simply create them by name, for example via this temporary code in your app delegate. CTFontRef font = CTFontCreateWithName&#40;CFSTR&#40;&#34;CharterITC-Regu&#34;&#41;, 20, NULL&#41;; NSLog&#40;@&#34;%@&#34;, font&#41;; If the font can be instantiated then the NSLog will output a description where you should see the same font name as in your creation statement. CTFont &#60;name: CharterITC-Regu, size: 20.000000, matrix: 0x0&#62; CTFontDescriptor &#60;attributes: &#60;CFBasicHash 0x7e24f60 [0x222fb48]&#62;{type = mutable dict, count = 1, entries =&#62; 1 : &#60;CFString 0x14ddc40 [0x222fb48]&#62;{contents = "NSFontNameAttribute"} = &#60;CFString 0x7e24d90 [0x222fb48]&#62;{contents = "CharterITC-Regu"} } Having verified that the font is available at run time you can now proceed to use it in text. Using the Custom Font When somebody says &#8220;I&#8217;m using this font&#8221; then he means &#8220;I am using the faces of this font family&#8221; because he expects that DTCoreText should select the appropriate font face based on whether or not regular or bold text is required. The selection process works by CSS styles, &#60;b&#62;, &#60;strong&#62;, &#60;em&#62; and &#60;i&#62; tags modifying a HTML tag&#8217;s fontDescriptor. When the NSAttributedString is being assembled then this local fontDescriptor is called with newMatchingFont to produce a font (or get one from cache) that matches the description. The modern way to specify a font for text in HTML is to apply a style: The (outdated) alternative &#8211; which is also still supported &#8211; is to specify the font face directly via the &#60;font&#62; tag. There the attribute name for the font family is &#8211; misleadingly &#8211; called &#8220;face&#8221;. Debugging Font Matching In Holger&#8217;s problem everything was set up correctly as described above, but still bold and regular text would end up using the same regular font face. Problems like this can happen if the font files come from a dubious source that didn&#8217;t take good care to set the font meta information correctly. There&#8217;s a simple check you can perform if you run into these kinds of problems with a custom font. Create a DTCoreTextFontDescriptor from the CTFont and output the CSS style representation. Or you just set a breakpoint after the creation of the descriptor and inspect its properties. DTCoreTextFontDescriptor *newDesc = &#91;&#91;DTCoreTextFontDescriptor alloc&#93; initWithCTFont:font&#93;; NSLog&#40;@&#34;%@&#34;, &#91;newDesc cssStyleRepresentation&#93;&#41;; In this example the output was: font-family:'Charter ITC';font-size:20px;font-weight:bold; So we see that even though we passed in the CharterITC-Regu from before this face appears to have a bold trait. This should not be and is a mistake. If both the regular font face and the bold one have the bold font trait then Core Text prefers the regular one. Workaround / Speed Improvement Since font matching is a painfully slow process I implemented a global font override table in DTCoreText. This override table is seeded with the contents of DTCoreTextFontOverrides.plist which contains the basic setup suitable for most preinstalled fonts on iOS. The override table specifies a combination of font family and bold and italic traits. When a bold face from a certain family is requested then DTCoreText can simple look up the font face name and create the CTFont from that. This is many times faster than doing a font search via Core Text. This is why I recommend that you include this plist with your app&#8217;s resources, if only for the faster font lookup. Without it all still works, but if you have many alternating fonts then this unnecessarily slows down your app. To get the same performance benefit for custom fonts you can simply add your custom font to the global override table. Incidentally this can also be used to work around fonts with incorrect traits. You should make these additions right after app launch, once a font has been matched it is cached and then this registration will be too late. // these fix the bold problem &#91;DTCoreTextFontDescriptor setOverrideFontName:@&#34;CharterITC-Bold&#34; forFontFamily:@&#34;Charter ITC&#34; bold:YES italic:NO&#93;; [...]]]></description>
				<content:encoded><![CDATA[<p>Friend of DTCoreText Holger was <a href="https://github.com/Cocoanetics/DTCoreText/issues/352">having problems</a> getting DTCoreText to use the bold font face of his custom font.</p>
<p>I want to take this opportunity to explain what the root cause for Holger&#8217;s problem was and what you need to know if you&#8217;re using custom fonts with DTCoreText.</p>
<p><span id="more-7854"></span></p>
<div id="more-7854"></div>
<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>
<p>DTCoreText has access to all the fonts that are installed on the iOS device, as well as those that you bundle with your app. Fonts are always grouped by <strong>Font Family</strong>. The individual looks are called <strong>Font Faces</strong>. Typically you will have 4 variants there: regular, bold, italic and bold+italic.</p>
<p>Apple&#8217;s Core Text system supports TrueType (TTF) as well as OpenType (OTF) fonts.</p>
<h3>Bundle the Font</h3>
<p>After copying the font files into your app, you assigning them to the target so that they get copied together with the other app resources. You have to register the font file names in your app&#8217;s info.plist so that they get loaded on app launch.</p>
<p>The font files go into the &#8220;Fonts provided by application&#8221; section, aka <strong>UIAppFonts</strong>.</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-20-at-14.56.40.png"><img class="alignnone  wp-image-7855" alt="Add fonts to info.plist" src="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-20-at-14.56.40.png?resize=631%2C269" data-recalc-dims="1" /></a></p>
<p>To check if the fonts get loaded correctly you can simply create them by name, for example via this temporary code in your app delegate.</p>

<div class="wp_codebox"><table><tr id="p785413"><td class="code" id="p7854code13"><pre class="objc" style="font-family:monospace;">CTFontRef font <span style="color: #002200;">=</span> CTFontCreateWithName<span style="color: #002200;">&#40;</span>CFSTR<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">&quot;CharterITC-Regu&quot;</span><span style="color: #002200;">&#41;</span>, <span style="color: #2400d9;">20</span>, <span style="color: #a61390;">NULL</span><span style="color: #002200;">&#41;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, font<span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>If the font can be instantiated then the NSLog will output a description where you should see the same font name as in your creation statement.</p>
<pre>CTFont &lt;name: CharterITC-Regu, size: 20.000000, matrix: 0x0&gt;
CTFontDescriptor &lt;attributes: &lt;CFBasicHash 0x7e24f60 [0x222fb48]&gt;{type = mutable dict, count = 1,
entries =&gt;
 1 : &lt;CFString 0x14ddc40 [0x222fb48]&gt;{contents = "NSFontNameAttribute"} = &lt;CFString 0x7e24d90 [0x222fb48]&gt;{contents = "CharterITC-Regu"}
}</pre>
<p>Having verified that the font is available at run time you can now proceed to use it in text.</p>
<h3>Using the Custom Font</h3>
<p>When somebody says <em>&#8220;I&#8217;m using this font&#8221;</em> then he means <em>&#8220;I am using the faces of this font family&#8221;</em> because he expects that DTCoreText should select the appropriate font face based on whether or not regular or bold text is required.</p>
<p>The selection process works by CSS styles, &lt;b&gt;, &lt;strong&gt;, &lt;em&gt; and &lt;i&gt; tags modifying a HTML tag&#8217;s fontDescriptor. When the NSAttributedString is being assembled then this local fontDescriptor is called with newMatchingFont to produce a font (or get one from cache) that matches the description.</p>
<p>The modern way to specify a font for text in HTML is to apply a style:</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-20-at-15.09.02.png"><img class="alignnone size-full wp-image-7856" alt="Font via Style" src="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-20-at-15.09.02.png?resize=615%2C108" data-recalc-dims="1" /></a></p>
<p>The (outdated) alternative &#8211; which is also still supported &#8211; is to specify the font face directly via the &lt;font&gt; tag. There the attribute name for the font family is &#8211; misleadingly &#8211; called &#8220;face&#8221;.</p>
<h3>Debugging Font Matching</h3>
<p>In Holger&#8217;s problem everything was set up correctly as described above, but still bold and regular text would end up using the same regular font face. Problems like this can happen if the font files come from a dubious source that didn&#8217;t take good care to set the font meta information correctly.</p>
<p>There&#8217;s a simple check you can perform if you run into these kinds of problems with a custom font. Create a DTCoreTextFontDescriptor from the CTFont and output the CSS style representation. Or you just set a breakpoint after the creation of the descriptor and inspect its properties.</p>

<div class="wp_codebox"><table><tr id="p785414"><td class="code" id="p7854code14"><pre class="objc" style="font-family:monospace;">DTCoreTextFontDescriptor <span style="color: #002200;">*</span>newDesc <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>DTCoreTextFontDescriptor alloc<span style="color: #002200;">&#93;</span> initWithCTFont<span style="color: #002200;">:</span>font<span style="color: #002200;">&#93;</span>;
NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;%@&quot;</span>, <span style="color: #002200;">&#91;</span>newDesc cssStyleRepresentation<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;</pre></td></tr></table></div>

<p>In this example the output was:</p>
<pre>font-family:'Charter ITC';font-size:20px;font-weight:bold;</pre>
<p>So we see that even though we passed in the CharterITC-Regu from before this face appears to have a bold trait. This should not be and is a mistake.</p>
<p>If both the regular font face and the bold one have the bold font trait then Core Text prefers the regular one.</p>
<h3>Workaround / Speed Improvement</h3>
<p>Since font matching is a painfully slow process I implemented a global font override table in DTCoreText. This override table is seeded with the contents of <strong>DTCoreTextFontOverrides.plist</strong> which contains the basic setup suitable for most preinstalled fonts on iOS.</p>
<p>The override table specifies a combination of font family and bold and italic traits. When a bold face from a certain family is requested then DTCoreText can simple look up the font face name and create the CTFont from that. This is many times faster than doing a font search via Core Text.</p>
<p>This is why I recommend that you include this plist with your app&#8217;s resources, if only for the faster font lookup. Without it all still works, but if you have many alternating fonts then this unnecessarily slows down your app.</p>
<p>To get the same performance benefit for custom fonts you can simply add your custom font to the global override table. Incidentally this can also be used to work around fonts with incorrect traits. You should make these additions right after app launch, once a font has been matched it is cached and then this registration will be too late.</p>

<div class="wp_codebox"><table><tr id="p785415"><td class="code" id="p7854code15"><pre class="objc" style="font-family:monospace;"><span style="color: #11740a; font-style: italic;">// these fix the bold problem</span>
<span style="color: #002200;">&#91;</span>DTCoreTextFontDescriptor setOverrideFontName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CharterITC-Bold&quot;</span> forFontFamily<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Charter ITC&quot;</span> bold<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span> italic<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>DTCoreTextFontDescriptor setOverrideFontName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CharterITC-BoldItal&quot;</span> forFontFamily<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Charter ITC&quot;</span> bold<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span> italic<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #11740a; font-style: italic;">// these are for completeness to get the faster lookup</span>
<span style="color: #002200;">&#91;</span>DTCoreTextFontDescriptor setOverrideFontName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CharterITC-Regu&quot;</span> forFontFamily<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Charter ITC&quot;</span> bold<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> italic<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#91;</span>DTCoreTextFontDescriptor setOverrideFontName<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;CharterITC-ReguItal&quot;</span> forFontFamily<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;Charter ITC&quot;</span> bold<span style="color: #002200;">:</span><span style="color: #a61390;">NO</span> italic<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>An alternative would be to add these 4 lines to the plist which you should be packaging with your app anyway. Though I slightly prefer the registration in code because if you use DTCoreText via CocoaPods you cannot modify the overrides plist file. But that&#8217;s your call.</p>
<h3>Conclusion</h3>
<p>When encountering font matching issues with external fonts you should first inspect the individual font faces if they possibly are having incorrectly specified traits. But in any case I recommend that you include the DTCoreText DemoApp&#8217;s font overrides plist with your app to speed up the matching. You can add your custom fonts in there or in code to have them included in the override process.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7854&amp;md5=0acedb5c71f1f5a23a10739a589aa238" 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/2013/03/using-custom-fonts-with-dtcoretext/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2013%2F03%2Fusing-custom-fonts-with-dtcoretext%2F&amp;language=en_GB&amp;category=text&amp;title=Using+Custom+Fonts+with+DTCoreText&amp;description=Friend+of+DTCoreText+Holger+was+having+problems+getting+DTCoreText+to+use+the+bold+font+face+of+his+custom+font.+I+want+to+take+this+opportunity+to+explain+what+the+root...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Today&#8217;s Hero: CHEN Xian&#8217;an</title>
		<link>http://www.cocoanetics.com/2013/03/todays-hero-chen-xianan/</link>
		<comments>http://www.cocoanetics.com/2013/03/todays-hero-chen-xianan/#comments</comments>
		<pubDate>Tue, 05 Mar 2013 18:17:33 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7723</guid>
		<description><![CDATA[I was having a problem in DTCoreText where the multi-byte sequence making up an Emoji would not get properly encoded by DTHTMLWriter. A quick peeking into NSHTMLWriter didn&#8217;t bring relief either, Apple is not encoding these characters, but leaves them unencoded. You can see in this screenshot that I looked at how NSHTMLWriter would encode two Emojis: That&#8217;s not the proper way for us, we want our output to be safe with any kind of transport encoding because it might end up on a machine that does not support UTF8 as brilliantly as iOS and OS X do. My first idea was that I might have to force the font family to be &#8220;Apple Color Emoji&#8221; which is the font that CoreText falls back to for displaying Emojis. However if you don&#8217;t have the proper encoding even setting the font family does not help. The problem was in NSString+HTML in DTCoreText which I use in DTHTMLWriter to add HTML entities. I created an issue on GitHub to describe my plight and while I was still dabbling around with libxml2 looking for an answer there Xian&#8217;an stepped in, fixed the bug and sent a pull request. Brilliant, simply brilliant! The solution is to use some wide unicode supporting methods found in Core Foundation, more precisely CFString. // ... looping through the unicars if (oneChar]]></description>
				<content:encoded><![CDATA[<p>I was having a problem in DTCoreText where the multi-byte sequence making up an Emoji would not get properly encoded by DTHTMLWriter. A quick peeking into NSHTMLWriter didn&#8217;t bring relief either, Apple is not encoding these characters, but leaves them unencoded.</p>
<p><span id="more-7723"></span></p>
<div id="more-7723"></div>
<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>
<p>You can see in this screenshot that I looked at how NSHTMLWriter would encode two Emojis:</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-05-at-7.04.01-PM.png"><img class="alignnone  wp-image-7724" alt="NSHTMLWriter Non-Encoding" src="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2013-03-05-at-7.04.01-PM.png?resize=614%2C537" data-recalc-dims="1" /></a></p>
<p>That&#8217;s not the proper way for us, we want our output to be safe with any kind of transport encoding because it might end up on a machine that does not support UTF8 as brilliantly as iOS and OS X do.</p>
<p>My first idea was that I might have to force the font family to be &#8220;Apple Color Emoji&#8221; which is the font that CoreText falls back to for displaying Emojis. However if you don&#8217;t have the proper encoding even setting the font family does not help.</p>
<p>The problem was in NSString+HTML in DTCoreText which I use in DTHTMLWriter to add HTML entities. I created an <a href="https://github.com/Cocoanetics/DTCoreText/issues/329">issue on GitHub</a> to describe my plight and while I was still dabbling around with libxml2 looking for an answer there Xian&#8217;an stepped in, fixed the bug and sent a pull request. Brilliant, simply brilliant!</p>
<p>The solution is to use some wide unicode supporting methods found in Core Foundation, more precisely CFString.</p>
<pre>
// ... looping through the unicars
if (oneChar<=255)
{
   [tmpString appendFormat:@"%C", oneChar];
}
else if (CFStringIsSurrogateHighCharacter(oneChar) &#038;&#038; i < [self length]-1)
{
   i++;
   unichar surrogateLowChar = [self characterAtIndex:i];
   UTF32Char u32code = CFStringGetLongCharacterForSurrogatePair(oneChar, surrogateLowChar);
   [tmpString appendFormat:@"&#%lu;", (unsigned long)u32code];
}
else
{
   [tmpString appendFormat:@"&#%d;", oneChar];
}
</pre>
<p>CFStringIsSurrogateHighCharacter checks if the current unichar character is a "Surrogate High Character". If yes then CFStringGetLongCharacterForSurrogatePair retrieves the 32-bit wide character value.</p>
<p>It's late, I'm tired and annoyed from having to re-tag DTCoreText 1.3.2 three times, but I just had to write this up for the whole world to know ...</p>
<p>Thank you <a href="https://twitter.com/_cxa">CHEN Xian'an</a>, your mad bug fixing skillz my day!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7723&amp;md5=92fcc2bc9b8adb1663b67a9975e98568" 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/2013/03/todays-hero-chen-xianan/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2013%2F03%2Ftodays-hero-chen-xianan%2F&amp;language=en_GB&amp;category=text&amp;title=Today%26%238217%3Bs+Hero%3A+CHEN+Xian%26%238217%3Ban&amp;description=I+was+having+a+problem+in+DTCoreText+where+the+multi-byte+sequence+making+up+an+Emoji+would+not+get+properly+encoded+by+DTHTMLWriter.+A+quick+peeking+into+NSHTMLWriter+didn%26%238217%3Bt+bring+relief...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Zarra on Locking</title>
		<link>http://www.cocoanetics.com/2013/02/zarra-on-locking/</link>
		<comments>http://www.cocoanetics.com/2013/02/zarra-on-locking/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 08:27:23 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7626</guid>
		<description><![CDATA[In my previous article dealing with Multi-Context Core Data I introduced a 3-context scheme that Marcus Zarra hat shown us in a back room at the 2012 NSConference. Several people inquired about Locking, take for example Wim Fikkert: Thanks for the great article. However, like Tom, I was wondering if the main context will not be blocked whenever you perform a save to disk with the persistent store. I am using the last design pattern, and I keep running into my app locking up. I have done some more searching and came across this article. Perhaps you can comment? I don&#8217;t pretend to come anywhere close to being the Core Data expert that Zarra is, so I went straight to the horses mouth and asked him. Marcus Zarra kindly responded shedding some light on the matter, emphasis mine. There is always a lot of confusion around locking. [Editor: DOH!] Whenever you save to the disk, no matter what context you are in, single or multiple, you are going to &#8220;lock&#8221; the NSPersistentStore while the write is taking place. That has always been true and most likely always will be true. What is not true is that the main context gets locked. That is a over-simplification of what happens. If, during a save, you attempt to fetch more data from disk then you will be blocked. That is the effect people are seeing and screaming about. Aha, so locking only affects a persistent store (aka the sqlite file). This is the 3-level approach I was referring to: Here we see that we only have writing access to the PSC (Persistent Store Coordinator) in the background writer context. In my Open Source DTDownloadCache I am doing the actual save to disk on a delayed timer that checks if there are changes and if there are any saves them. So what about all those other copies of the data that is already in memory? However, if you are working with data that is already in memory then you won&#8217;t be blocked. Also, depending on what you are fetching and how your fetch is configured, you can do a fetch that doesn&#8217;t block because the data is already in disk. That is harder to accomplish though so I relegate it to a side point. I should note that the default for a NSFetchRequest is to hit disk no matter what (this is the staleness interval) The core problem is the locking of the NSPersistentStore. Since that cannot be avoided it needs to be lessened. To do that you spread it out into smaller hits so that the main (or other) contexts have a chance to get in and retrieve data frequently enough that the user does not get the sensation of &#8220;locking&#8221;. Small/frequent saves during imports is a common solution. Now reading access is something that might cause a pause when NSFetchedResultsController cannot find current data in the Main MOC. Then it has to inquire its parent context for the data which has to get it from disk. And of course Zarra also has an alternative but he doubts the viability of that even himself: Another solution that is a bit hairy is to have *two* NSPersistentStoreCoordinator instances, one for writing one for reading. However that gets very complex very fast and I never recommend it. With a double PSC design you must tell the primary context when things change because it has no automatic notification. I mention it for completeness of the answer as opposed to a suggestion. I have yet to see that solution end well Let&#8217;s recap: writing to disk = locking the store, always accessing data already in memory does not lock inside the staleness interval, otherwise is has to go up the chain an eventually get fresh data from disk importing data = small/frequent saves (decoupled as shown above) My personal conclusion is that you&#8217;ll have to experiment with how frequent you call a save on the Managed Object Context that is connected to your persistent store. There might be scenarios where you can get away with saving all the time and other where you should wait for an opportune moment in UI interaction when the user wouldn&#8217;t notice a slight pause on the main thread. Thank you Marcus Zarra for your generously dispensed insight!]]></description>
				<content:encoded><![CDATA[<p>In my previous article dealing with <a title="Multi-Context CoreData" href="http://www.cocoanetics.com/2012/07/multi-context-coredata/">Multi-Context Core Data</a> I introduced a 3-context scheme that <a href="http://www.cimgf.com">Marcus Zarra</a> hat shown us in a back room at the 2012 NSConference.</p>
<p>Several people inquired about Locking, take for example Wim Fikkert:</p>
<blockquote><p>Thanks for the great article. However, like Tom, I was wondering if the main context will not be blocked whenever you perform a save to disk with the persistent store. I am using the last design pattern, and I keep running into my app locking up. I have done some more searching and came across <a href="http://wbyoung.tumblr.com/post/27851725562/core-data-growing-pains">this article</a>. Perhaps you can comment?</p></blockquote>
<p>I don&#8217;t pretend to come anywhere close to being the Core Data expert that Zarra is, so I went straight to the horses mouth and asked him.</p>
<p><span id="more-7626"></span></p>
<div id="more-7626"></div>
<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>
<p>Marcus Zarra kindly responded shedding some light on the matter, emphasis mine.</p>
<blockquote><p>There is always a lot of confusion around locking. [Editor: DOH!]</p>
<p><strong>Whenever you save to the disk</strong>, no matter what context you are in, single or multiple, you are going to <strong>&#8220;lock&#8221; the NSPersistentStore while the write is taking place</strong>. That has always been true and most likely always will be true.</p>
<p>What is not true is that the main context gets locked. That is a over-simplification of what happens. If, during a save, you attempt to fetch more data from disk then you will be blocked. That is the effect people are seeing and screaming about.</p></blockquote>
<p>Aha, so locking only affects a persistent store (aka the sqlite file). This is the 3-level approach I was referring to:</p>
<p><img class="alignnone size-full wp-image-6763" title="Supercharged Background Writing" alt="" src="http://i2.wp.com/www.cocoanetics.com/files/Bildschirmfoto-2012-07-18-um-4.14.55-PM.png?resize=511%2C549" data-recalc-dims="1" /></p>
<p>Here we see that we only have <em>writing access</em> to the PSC (Persistent Store Coordinator) in the background writer context. In my Open Source DTDownloadCache I am doing the actual save to disk on a delayed timer that checks if there are changes and if there are any saves them.</p>
<p>So what about all those other copies of the data that is already in memory?</p>
<blockquote><p>However, if you are working with data that is <strong>already in memory then you won&#8217;t be blocked</strong>.</p>
<p>Also, depending on what you are fetching and how your fetch is configured, you can do a fetch that doesn&#8217;t block because the data is already in disk. That is harder to accomplish though so I relegate it to a side point. I should note that the default for a NSFetchRequest is to hit disk no matter what (this is the staleness interval)</p>
<p>The core problem is the locking of the NSPersistentStore. Since that cannot be avoided it needs to be lessened. To do that you spread it out into smaller hits so that the main (or other) contexts have a chance to get in and retrieve data frequently enough that the user does not get the sensation of &#8220;locking&#8221;. <strong>Small/frequent saves during imports</strong> is a common solution.</p></blockquote>
<p>Now <em>reading access</em> is something that might cause a pause when NSFetchedResultsController cannot find current data in the Main MOC. Then it has to inquire its parent context for the data which has to get it from disk.</p>
<p>And of course Zarra also has an alternative but he doubts the viability of that even himself:</p>
<blockquote><p>Another solution that is a bit hairy is to have *two* NSPersistentStoreCoordinator instances, one for writing one for reading. However that gets <strong>very complex very fast and I never recommend it</strong>. With a double PSC design you must tell the primary context when things change because it has no automatic notification. I mention it for completeness of the answer as opposed to a suggestion. I have yet to see that solution end well <img src='http://i1.wp.com/www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' data-recalc-dims="1" /> </p></blockquote>
<p>Let&#8217;s recap:</p>
<ul>
<li>writing to disk = locking the store, always</li>
<li>accessing data already in memory does not lock inside the staleness interval, otherwise is has to go up the chain an eventually get fresh data from disk</li>
<li>importing data = small/frequent saves (decoupled as shown above)</li>
</ul>
<p>My personal conclusion is that you&#8217;ll have to experiment with how frequent you call a save on the Managed Object Context that is connected to your persistent store. There might be scenarios where you can get away with saving all the time and other where you should wait for an opportune moment in UI interaction when the user wouldn&#8217;t notice a slight pause on the main thread.</p>
<p>Thank you Marcus Zarra for your generously dispensed insight!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7626&amp;md5=b613adc095fb6bfd75c21ed9729b7b9b" 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/2013/02/zarra-on-locking/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2013%2F02%2Fzarra-on-locking%2F&amp;language=en_GB&amp;category=text&amp;title=Zarra+on+Locking&amp;description=In+my+previous+article+dealing+with+Multi-Context+Core+Data%C2%A0I+introduced+a+3-context+scheme+that+Marcus+Zarra%C2%A0hat+shown+us+in+a+back+room+at+the+2012+NSConference.+Several+people+inquired+about...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>How to send image to remote server</title>
		<link>http://www.cocoanetics.com/2013/01/how-to-send-image-to-remote-server/</link>
		<comments>http://www.cocoanetics.com/2013/01/how-to-send-image-to-remote-server/#comments</comments>
		<pubDate>Fri, 11 Jan 2013 07:14:24 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7443</guid>
		<description><![CDATA[Somebody asked on StackOverflow: how to send image to Remote server from the below code last string is placed with image NSString *reqString=[NSString stringWithFormat:@"http://projeceads.info/spir/productinfo/productadd/%@/%@/%@/%@/%@/%@/%@/%@",ownerId,productNameTxt.text,QuantityTxt.text,sizeTxt.text,ageTxt.text,priceTxt.text,descriptionView.text,imgstr]; NSURL *reqUrl=[NSURL URLWithString:reqString]; NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:reqUrl] delegate:self]; [connection start]; } Now there are several things wrong with this question. This is the very first question this person asked on StackOverflow and he didn&#8217;t even set a proper user name yet. The code is not formatted as such, the English is bad and to most casual onlookers it is unclear what this question is about. Still I felt an urge to give a good answer because often it is non-sensical questions like this that challenge our ability to parse the intent of the asking person and our knowledge of the subject matter. It is also such a situation where you can give an answer that exactly matches the question as well as a second answer that is a better way of achieving the intent. There are two ways how you can upload data to a web server: GET or POST With GET you have to put all information that you want the web server to have into the URL. With POST you additionally can put information into the POST body. From your question I deduct that he seems to try to upload the image via a GET request and thus needs to &#8220;append the image to the URL&#8221;. An image as such is binary data, either uncompressed as RGBA values, usually 1 byte each times width times height. Since this is too much data for most uses, people like to compress images. UIImagePNGRepresentation allows you to create the data in PNG or JPEG format. But even this compressed format is might not transferable via HTTP if your webserver is unable to process binary data. Historically you have not been able to use all values a byte can hold (0-255) in HTTP which itself is a pure text format. Originally HTTP was only using 7-bit ASCII characters (0-127) which are safe to be transmitted. Because of this any binary data you want to send somewhere has to be encoded into a representation that only uses safe characters. The most prevalent such encoding scheme is &#8220;base64&#8243;. One drawback of base64 encoding is that it increases the amount of data you need to send by about a third. Also most modern web servers can actually receive binary post data which is why in the following article I did not need to encode the image. I wrote up here how to upload an image via POST to TwitPic. You need to put together the correct headers and compose a POST body as shown here: http://www.cocoanetics.com/2010/02/uploading-uiimages-to-twitpic/ This is the way I would recommend you upload your image as well, if your web server supports it. This is not the answer you are looking for, but it is the approach you SHOULD take. Now to actually answer your question &#8220;how do I create a URL that includes a representation of an image&#8221; (because my server admin is too stupid to build me a script that would also accept a POST)&#8230; The steps are: Create a compressed representation with UIImage&#8230;Representation Base64-encode the output from 1 URL-encode the output from 2 append to URL string send GET request For base64-encoding I use a method created by famous Matt Gallagher. URL-encoding is necessary because even less characters are legal to use in well-formed URLs than are in 7-bit HTTP. For URL-encoding I use this NSString category. Summary Even though it is possible you should not send images via GET URLs. Send them like normal people as POST requests and put the image data into the POST body in either binary or base64-encoded format. The steps are: Create a compressed representation with UIImage&#8230;Representation Base64-encode the output from 1 (optional, if your web server doesn&#8217;t support binary or you want to be safe) construct content headers append POST body send POST request PS: Of course you can also use one of the many networking frameworks out there for constructing POST requests. But I can guarantee that you will not find a single one that will allow your to append a textual-doubly-encoded image representation to the GET URL.]]></description>
				<content:encoded><![CDATA[<p>Somebody <a href="http://stackoverflow.com/questions/14272660/how-to-send-image-to-remote-server/14273255#14273255">asked on StackOverflow</a>:</p>
<blockquote style="white-space:pre-wrap"><p>how to send image to Remote server from the below code last string is placed with image</p>
<p>NSString *reqString=[NSString stringWithFormat:@"http://projeceads.info/spir/productinfo/productadd/%@/%@/%@/%@/%@/%@/%@/%@",ownerId,productNameTxt.text,QuantityTxt.text,sizeTxt.text,ageTxt.text,priceTxt.text,descriptionView.text,imgstr]; NSURL *reqUrl=[NSURL URLWithString:reqString]; NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:reqUrl] delegate:self];<br />
[connection start]; }</p></blockquote>
<p>Now there are several things wrong with this question. This is the very first question this person asked on StackOverflow and he didn&#8217;t even set a proper user name yet. The code is not formatted as such, the English is bad and to most casual onlookers it is unclear what this question is about.</p>
<p>Still I felt an urge to give a good answer because often it is non-sensical questions like this that challenge our ability to parse the intent of the asking person and our knowledge of the subject matter. It is also such a situation where you can give an answer that exactly matches the question as well as a second answer that is a better way of achieving the intent.</p>
<p><span id="more-7443"></span></p>
<div id="more-7443"></div>
<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>
<p>There are two ways how you can upload data to a web server: GET or POST</p>
<p>With GET you have to put all information that you want the web server to have into the URL. With POST you additionally can put information into the POST body.</p>
<p>From your question I deduct that he seems to try to upload the image via a GET request and thus needs to &#8220;append the image to the URL&#8221;.</p>
<p>An image as such is binary data, either uncompressed as RGBA values, usually 1 byte each times width times height. Since this is too much data for most uses, people like to compress images. UIImagePNGRepresentation allows you to create the data in PNG or JPEG format.</p>
<p>But even this compressed format is might not transferable via HTTP if your webserver is unable to process binary data. Historically you have not been able to use all values a byte can hold (0-255) in HTTP which itself is a pure text format. Originally HTTP was only using 7-bit ASCII characters (0-127) which are safe to be transmitted. Because of this any binary data you want to send somewhere has to be encoded into a representation that only uses safe characters. The most prevalent such encoding scheme is &#8220;base64&#8243;.</p>
<p>One drawback of base64 encoding is that it increases the amount of data you need to send by about a third. Also most modern web servers can actually receive binary post data which is why in the following article I did not need to encode the image. I wrote up here how to upload an image via POST to TwitPic. You need to put together the correct headers and compose a POST body as shown here: <a href="http://www.cocoanetics.com/2010/02/uploading-uiimages-to-twitpic/" rel="nofollow">http://www.cocoanetics.com/2010/02/uploading-uiimages-to-twitpic/</a></p>
<p>This is the way I would recommend you upload your image as well, if your web server supports it. This is not the answer you are looking for, but it is the approach you SHOULD take.</p>
<p>Now to actually answer your question &#8220;how do I create a URL that includes a representation of an image&#8221; (because my server admin is too stupid to build me a script that would also accept a POST)&#8230;</p>
<p>The steps are:</p>
<ol>
<li>Create a compressed representation with UIImage&#8230;Representation</li>
<li>Base64-encode the output from 1</li>
<li>URL-encode the output from 2</li>
<li>append to URL string</li>
<li>send GET request</li>
</ol>
<p>For base64-encoding I use a <a href="https://github.com/Cocoanetics/DTFoundation/blob/master/Core/Source/NSData%2BBase64.h">method created by famous Matt Gallagher</a>. URL-encoding is necessary because even less characters are legal to use in well-formed URLs than are in 7-bit HTTP. For URL-encoding I use <a href="https://github.com/Cocoanetics/DTFoundation/blob/master/Core/Source/NSString%2BDTURLEncoding.h">this NSString category</a>.</p>
<h3>Summary</h3>
<p>Even though it is possible you should <em>not</em> send images via GET URLs. Send them like normal people as POST requests and put the image data into the POST body in either binary or base64-encoded format.</p>
<p>The steps are:</p>
<ol>
<li>Create a compressed representation with UIImage&#8230;Representation</li>
<li>Base64-encode the output from 1 (optional, if your web server doesn&#8217;t support binary or you want to be safe)</li>
<li>construct content headers</li>
<li>append POST body</li>
<li>send POST request</li>
</ol>
<p>PS: Of course you can also use one of the many networking frameworks out there for constructing POST requests. But I can guarantee that you will not find a single one that will allow your to append a textual-doubly-encoded image representation to the GET URL.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7443&amp;md5=40d896e25c3d5f9a1ada2317eefc11a1" 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/2013/01/how-to-send-image-to-remote-server/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2013%2F01%2Fhow-to-send-image-to-remote-server%2F&amp;language=en_GB&amp;category=text&amp;title=How+to+send+image+to+remote+server&amp;description=Somebody+asked+on+StackOverflow%3A+how+to+send+image+to+Remote+server+from+the+below+code+last+string+is+placed+with+image+NSString+%2AreqString%3D%5BNSString+stringWithFormat%3A%40%22http%3A%2F%2Fprojeceads.info%2Fspir%2Fproductinfo%2Fproductadd%2F%25%40%2F%25%40%2F%25%40%2F%25%40%2F%25%40%2F%25%40%2F%25%40%2F%25%40%22%2CownerId%2CproductNameTxt.text%2CQuantityTxt.text%2CsizeTxt.text%2CageTxt.text%2CpriceTxt.text%2CdescriptionView.text%2Cimgstr%5D%3B+NSURL+%2AreqUrl%3D%5BNSURL+URLWithString%3AreqString%5D%3B+NSURLConnection+%2Aconnection%3D%5B%5BNSURLConnection+alloc%5DinitWithRequest%3A%5BNSURLRequest...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Assorted Observations</title>
		<link>http://www.cocoanetics.com/2012/10/assorted-observations/</link>
		<comments>http://www.cocoanetics.com/2012/10/assorted-observations/#comments</comments>
		<pubDate>Fri, 12 Oct 2012 11:57:54 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=7130</guid>
		<description><![CDATA[While I am developing my first own Mac app I&#8217;ve been adding to this blog post whenever something was weird to me. Or simply different. You can definitely see in many instances how some modus operandi on iOS has its roots on Mac, but Apple had to change things a bit around to accomodate the different UI paradigms on the mobile platform. CG versus NS You will find that AppKit uses structs for everything that are prefixed with NS, even though the contents are identical. In many cases you can assign a CGRect to an NSRect though that would disturb purists. There are a plethora of macros to move between these worlds. So you better use these so that if somebody reads your code does not get the impression you don&#8217;t know what you are doing. Upside Down NSViews have the origin of their coordinate system in the lower left corner of the view. On UIKit we are used to origin being in the upper left corner. Fortunately there&#8217;s a simple trick to flip the coordinate system. In your NSView subclass add this: - &#40;BOOL&#41;isFlipped &#123; return YES; &#125; Henceforth all added sub views will be positioned just like on iOS. Since the default implementation of this method returns NO you can only make this modification to your own sub-classes. Basic Drawing Like on iOS you have two way of drawing stuff. You can act on the higher level Objective-C API of AppKit/UIKit or you can go down to the Quartz level. Internally all drawing gets mapped to Quartz anyway, so if you already have such lower-level code you can easily transfer it, though you might have to be careful about the coordinate system flipping. To draw a simple rectangle at the corner of the NSView you can do that in AppKit: - &#40;void&#41;drawRect:&#40;NSRect&#41;dirtyRect &#123; &#91;&#91;NSColor redColor&#93; set&#93;; &#91;NSBezierPath strokeRect:self.bounds&#93;; &#125; Or in Quartz: - &#40;void&#41;drawRect:&#40;NSRect&#41;dirtyRect &#123; CGContextRef context = &#91;&#91;NSGraphicsContext currentContext&#93; graphicsPort&#93;; &#160; CGContextSetRGBStrokeColor&#40;context, 1.0, 0, 0, 1.0&#41;; CGContextStrokeRect&#40;context, self.bounds&#41;; &#125; The main difference is that you have to obtain the CGContext reference from the current NSGraphicsContext as opposed to UIGraphicsGetCurrentContext. Without isFlipped:YES both AppKit and Quartz have the lower left origin. On iOS Quartz draws from the lower left corner, UIKit from the upper left corner. You might remember having to the coordinate system for Quartz drawing on iOS by means of a transform. Drop a Shadow To drop a shadow behind an NSImage you can use the NSShadow class. Similar to NSColors you can also simply &#8220;set&#8221; the shadow instance on the graphics context. - &#40;void&#41;drawRect:&#40;NSRect&#41;dirtyRect &#123; NSShadow *shadow = &#91;&#91;NSShadow alloc&#93; init&#93;; &#91;shadow setShadowColor: &#91;NSColor colorWithDeviceWhite: 0.0f alpha: 1.0f&#93;&#93;; &#91;shadow setShadowBlurRadius: 5.0f&#93;; &#91;_shadow setShadowOffset: NSMakeSize&#40;0, -1&#41;&#93;; &#91;shadow set&#93;; &#91;_pageImage drawInRect:&#91;self _rectForPage&#93; fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0&#93;; &#125; This creates a shadow and the subsequent drawing operations will show it. Be careful however, because on Mac graphics contexts sometimes get reused. Clean Up After Yourself NSPageController creates a snapshot of the view that is going out and the one that is appearing. One thing that was not obvious to me was that it reuses the graphics context used to draw its content view. The page view would be drawn once and as soon as you started to move your finger it would create another snapshot reusing the graphics context we previously set the shadow on. You see that the gray area in the dashed red box is blurry and so is the page corner where I am drawing a red line for debug purposes. I was puzzled at first because on iOS you don&#8217;t ever see a graphics being reused like this. The solution &#8211; of course &#8211; is to save the graphics state before making changes to it and restore that state when you&#8217;re done drawing. - &#40;void&#41;drawRect:&#40;NSRect&#41;dirtyRect &#123; NSGraphicsContext* context = &#91;NSGraphicsContext currentContext&#93;; &#91;context saveGraphicsState&#93;; &#160; &#91;&#91;self shadow&#93; set&#93;; &#91;_pageImage drawInRect:&#91;self _rectForPage&#93; fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0&#93;; &#160; &#91;context restoreGraphicsState&#93;; &#125; That fixes the problem nicely. So we can concluded that it is probably generally good citizenship to clean up changes to the graphics context. Layer or No Layer? The red dashed boxes you see in the screenshots are subviews of the large page view. With half an ear I had heard that since quite recently OS X can also back NSViews with CoreAnimation layers. This always has been the only way on iOS. You can activate this layer-backing mode by setting the wantsLayer property to YES. I figured that layers must be better, so I turned it on for the subviews. Now I was seeing another strange effect together with the NSPageController. The snapshot for the pages would only include the boxes that where present on screen when you started the swiping motion on the trackpad. When I disabled the layer-backing suddenly the snapshots would also properly include [...]]]></description>
				<content:encoded><![CDATA[<p>While I am developing my first own Mac app I&#8217;ve been adding to this blog post whenever something was weird to me. Or simply different.</p>
<p>You can definitely see in many instances how some modus operandi on iOS has its roots on Mac, but Apple had to change things a bit around to accomodate the different UI paradigms on the mobile platform.</p>
<p><span id="more-7130"></span></p>
<div id="more-7130"></div>
<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>
<h3>CG versus NS</h3>
<p>You will find that AppKit uses structs for everything that are prefixed with NS, even though the contents are identical. In many cases you can assign a CGRect to an NSRect though that would disturb purists.</p>
<p>There are a plethora of macros to move between these worlds. So you better use these so that if somebody reads your code does not get the impression you don&#8217;t know what you are doing.</p>
<h3>Upside Down</h3>
<p>NSViews have the origin of their coordinate system in the lower left corner of the view. On UIKit we are used to origin being in the upper left corner. Fortunately there&#8217;s a simple trick to flip the coordinate system.</p>
<p>In your NSView subclass add this:</p>

<div class="wp_codebox"><table><tr id="p713027"><td class="code" id="p7130code27"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>isFlipped
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Henceforth all added sub views will be positioned just like on iOS. Since the default implementation of this method returns NO you can only make this modification to your own sub-classes.</p>
<h3>Basic Drawing</h3>
<p>Like on iOS you have two way of drawing stuff. You can act on the higher level Objective-C API of AppKit/UIKit or you can go down to the Quartz level. Internally all drawing gets mapped to Quartz anyway, so if you already have such lower-level code you can easily transfer it, though you might have to be careful about the coordinate system flipping.</p>
<p>To draw a simple rectangle at the corner of the NSView you can do that in AppKit:</p>

<div class="wp_codebox"><table><tr id="p713028"><td class="code" id="p7130code28"><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>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRect</span><span style="color: #002200;">&#41;</span>dirtyRect
<span style="color: #002200;">&#123;</span>
	<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSColor_Class/"><span style="color: #400080;">NSColor</span></a> redColor<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBezierPath_Class/"><span style="color: #400080;">NSBezierPath</span></a> strokeRect<span style="color: #002200;">:</span>self.bounds<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Or in Quartz:</p>

<div class="wp_codebox"><table><tr id="p713029"><td class="code" id="p7130code29"><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>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRect</span><span style="color: #002200;">&#41;</span>dirtyRect
<span style="color: #002200;">&#123;</span>
	CGContextRef context <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/ApplicationKit/Classes/NSGraphicsContext_Class/"><span style="color: #400080;">NSGraphicsContext</span></a> currentContext<span style="color: #002200;">&#93;</span> graphicsPort<span style="color: #002200;">&#93;</span>;
&nbsp;
	CGContextSetRGBStrokeColor<span style="color: #002200;">&#40;</span>context, <span style="color: #2400d9;">1.0</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">0</span>, <span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#41;</span>;
	CGContextStrokeRect<span style="color: #002200;">&#40;</span>context, self.bounds<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>The main difference is that you have to obtain the CGContext reference from the current NSGraphicsContext as opposed to UIGraphicsGetCurrentContext. Without isFlipped:YES both AppKit and Quartz have the lower left origin. On iOS Quartz draws from the lower left corner, UIKit from the upper left corner. You might remember having to the coordinate system for Quartz drawing on iOS by means of a transform.</p>
<h3>Drop a Shadow</h3>
<p>To drop a shadow behind an NSImage you can use the NSShadow class. Similar to NSColors you can also simply &#8220;set&#8221; the shadow instance on the graphics context.</p>

<div class="wp_codebox"><table><tr id="p713030"><td class="code" id="p7130code30"><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>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRect</span><span style="color: #002200;">&#41;</span>dirtyRect
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSShadow_Class/"><span style="color: #400080;">NSShadow</span></a> <span style="color: #002200;">*</span>shadow <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/ApplicationKit/Classes/NSShadow_Class/"><span style="color: #400080;">NSShadow</span></a> alloc<span style="color: #002200;">&#93;</span> init<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>shadow setShadowColor<span style="color: #002200;">:</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSColor_Class/"><span style="color: #400080;">NSColor</span></a> colorWithDeviceWhite<span style="color: #002200;">:</span> 0.0f alpha<span style="color: #002200;">:</span> 1.0f<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>shadow setShadowBlurRadius<span style="color: #002200;">:</span> 5.0f<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_shadow setShadowOffset<span style="color: #002200;">:</span> NSMakeSize<span style="color: #002200;">&#40;</span><span style="color: #2400d9;">0</span>, <span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>shadow set<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_pageImage drawInRect<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self _rectForPage<span style="color: #002200;">&#93;</span> fromRect<span style="color: #002200;">:</span>NSZeroRect operation<span style="color: #002200;">:</span>NSCompositeCopy fraction<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>This creates a shadow and the subsequent drawing operations will show it. Be careful however, because on Mac graphics contexts sometimes get reused.</p>
<h3>Clean Up After Yourself</h3>
<p>NSPageController creates a snapshot of the view that is going out and the one that is appearing. One thing that was not obvious to me was that it reuses the graphics context used to draw its content view.</p>
<p>The page view would be drawn once and as soon as you started to move your finger it would create another snapshot reusing the graphics context we previously set the shadow on. You see that the gray area in the dashed red box is blurry and so is the page corner where I am drawing a red line for debug purposes.</p>
<p><a href="http://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2012-10-05-at-11.02.37-AM.png"><img class="alignnone size-full wp-image-7131" title="Evidence of reused graphics context" src="http://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2012-10-05-at-11.02.37-AM.png?resize=440%2C324" alt="" data-recalc-dims="1" /></a></p>
<p>I was puzzled at first because on iOS you don&#8217;t ever see a graphics being reused like this. The solution &#8211; <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaDrawingGuide/GraphicsContexts/GraphicsContexts.html">of course</a> &#8211; is to save the graphics state before making changes to it and restore that state when you&#8217;re done drawing.</p>

<div class="wp_codebox"><table><tr id="p713031"><td class="code" id="p7130code31"><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>drawRect<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">NSRect</span><span style="color: #002200;">&#41;</span>dirtyRect
<span style="color: #002200;">&#123;</span>
	<a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSGraphicsContext_Class/"><span style="color: #400080;">NSGraphicsContext</span></a><span style="color: #002200;">*</span> context <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSGraphicsContext_Class/"><span style="color: #400080;">NSGraphicsContext</span></a> currentContext<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>context saveGraphicsState<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self shadow<span style="color: #002200;">&#93;</span> set<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#91;</span>_pageImage drawInRect<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self _rectForPage<span style="color: #002200;">&#93;</span> fromRect<span style="color: #002200;">:</span>NSZeroRect operation<span style="color: #002200;">:</span>NSCompositeCopy fraction<span style="color: #002200;">:</span><span style="color: #2400d9;">1.0</span><span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #002200;">&#91;</span>context restoreGraphicsState<span style="color: #002200;">&#93;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>That fixes the problem nicely.</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2012-10-05-at-11.08.21-AM.png"><img class="alignnone size-full wp-image-7132" title="No superfluous shadow" src="http://i1.wp.com/www.cocoanetics.com/files/Screen-Shot-2012-10-05-at-11.08.21-AM.png?resize=397%2C270" alt="" data-recalc-dims="1" /></a></p>
<p>So we can concluded that it is probably generally good citizenship to clean up changes to the graphics context.</p>
<h3>Layer or No Layer?</h3>
<p>The red dashed boxes you see in the screenshots are subviews of the large page view. With half an ear I had heard that since quite recently OS X can also back NSViews with CoreAnimation layers. This always has been the only way on iOS.</p>
<p>You can activate this layer-backing mode by setting the wantsLayer property to YES. I figured that layers must be better, so I turned it on for the subviews.</p>
<p>Now I was seeing another strange effect together with the NSPageController. The snapshot for the pages would only include the boxes that where present on screen when you started the swiping motion on the trackpad.</p>
<p>When I disabled the layer-backing suddenly the snapshots would also properly include the sub-views. If you know why this is and maybe can explain the advantages of using layer-backing then please speak up!</p>
<h3>Difference in Animation</h3>
<p>One explanation for many differences is the simple fact that all views on iOS only ever WHERE layer-backed. Whereas you only are beginning to get this as an option on OS X since 10.7. You can see many places where stock-controls show weird artifacts when used in a layer-hierarchy. Any layer that you make layer-backed view (via setWantsLayer:YES) will automatically pass on the setting to all of its subviews.</p>
<p>Now if you are using some ancient UI controls down the layer-hierarchy, like for example NSTextField there are situations where you see that it is unable to properly draw itself.</p>
<p>Animations on iOS are usually done by simply setting a property value. This triggers an implicit animation with a duration of like 25 ms. If you are resizing an UIImageView like this then CoreAnimation will take care of the animation frames between start and finish. All the while you already see the final value on the property.</p>
<p>On Mac Animations existed since long before there where CALayers, CA as in Core Animation. There a frame change is actually done by calling the animator of a view and setting the property there. This will then take care of setting a different frame for each animation step and the view redrawing itself.</p>

<div class="wp_codebox"><table><tr id="p713032"><td class="code" id="p7130code32"><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>layoutSubviewsAnimated<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: #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: #11740a; font-style: italic;">// temporarily set the document view frame to the entire contianer, to avoid flicker at bottom section</span>
		<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self documentView<span style="color: #002200;">&#93;</span> setFrame<span style="color: #002200;">:</span>self.bounds<span style="color: #002200;">&#93;</span>;
&nbsp;
		<span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAnimationContext_Class/"><span style="color: #400080;">NSAnimationContext</span></a> beginGrouping<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAnimationContext_Class/"><span style="color: #400080;">NSAnimationContext</span></a> currentContext<span style="color: #002200;">&#93;</span> setDuration<span style="color: #002200;">:</span>kDMPaletteContainerAnimationDuration<span style="color: #002200;">&#93;</span>;
		<span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAnimationContext_Class/"><span style="color: #400080;">NSAnimationContext</span></a> currentContext<span style="color: #002200;">&#93;</span> setCompletionHandler<span style="color: #002200;">:^</span><span style="color: #002200;">&#123;</span>
		<span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
&nbsp;
    <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/"><span style="color: #400080;">NSSortDescriptor</span></a> <span style="color: #002200;">*</span>sortDescriptor <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/"><span style="color: #400080;">NSSortDescriptor</span></a> sortDescriptorWithKey<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;index&quot;</span> ascending<span style="color: #002200;">:</span><span style="color: #a61390;">YES</span><span style="color: #002200;">&#93;</span>;
    contentSectionViews <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>contentSectionViews sortedArrayUsingDescriptors<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>sortDescriptor<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
&nbsp;
    <span style="color: #002200;">&#91;</span>contentSectionViews enumerateObjectsUsingBlock<span style="color: #002200;">:^</span><span style="color: #002200;">&#40;</span>DMPaletteSectionView<span style="color: #002200;">*</span> paletteSection, NSUInteger idx, <span style="color: #a61390;">BOOL</span> <span style="color: #002200;">*</span>stop<span style="color: #002200;">&#41;</span> <span style="color: #002200;">&#123;</span>
		 <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><span style="color: #002200;">&#91;</span>paletteSection animator<span style="color: #002200;">&#93;</span> setFrame<span style="color: #002200;">:</span><span style="color: #002200;">&#91;</span>self frameForSectionAtIndex<span style="color: #002200;">:</span>idx<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#93;</span>;
		 <span style="color: #002200;">&#125;</span>
		 <span style="color: #a61390;">else</span>
		 <span style="color: #002200;">&#123;</span>
			 paletteSection.frame <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>self frameForSectionAtIndex<span style="color: #002200;">:</span>idx<span style="color: #002200;">&#93;</span>;
		 <span style="color: #002200;">&#125;</span>
    <span style="color: #002200;">&#125;</span><span style="color: #002200;">&#93;</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><a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAnimationContext_Class/"><span style="color: #400080;">NSAnimationContext</span></a> endGrouping<span style="color: #002200;">&#93;</span>;
	<span style="color: #002200;">&#125;</span>
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>It makes me smile to see the possibility of adding a completion handler to the animation group set up here. A sign of new tech infusing the tried and true approach.</p>
<p>If you appreciate this difference in how animations occur in iOS versus traditional OS X then you begin to understand why Apple could never have pulled off the responsiveness of iOS with animators. Only Core Animation and layer animations allow for doing all sorts of tricks on the GPU to scale the contents of layers/views.</p>
<h3>First Responder, WTF?</h3>
<p>On iOS you might have made a view first responder a few times before, usually you would do that with a UITextView to have the keyboard show. Also there we resigned to the fact there there is no public method to get the current first responder, but we are content with that since becomeFirstResponder automatically resigns the current first responder from its status before the new view becomes the new one.</p>
<p>On Mac it is sufficient for the user to click on any view and it will be made first responder, provided that it responds with acceptsFirstResponder YES. If not then the click will <a title="The Amazing Responder Chain" href="http://www.cocoanetics.com/2012/09/the-amazing-responder-chain/">travel up the responder chain</a> and the next view responding with YES will be it. Since you can have multiple windows visible on Mac at the same time, each window has its own first responder which you can inquire from the window.</p>
<p>Setting a first responder in code is also slightly different than on iOS. There the NSWindow instance provides a method to set the first responder. According to the docs this sends resignFirstResponder to the current one and then &#8211; if that was successful &#8211; asks the new one to becomeFirstResonder.</p>

<div class="wp_codebox"><table><tr id="p713033"><td class="code" id="p7130code33"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self mainDocumentWindowController<span style="color: #002200;">&#93;</span>.window makeFirstResponder<span style="color: #002200;">:</span>pageView<span style="color: #002200;">&#93;</span>;</pre></td></tr></table></div>

<p>What I don&#8217;t yet understand is why in my experiments a becomeFirstResponder often did work, but not always. For example an NSPageController seems to not relinquish first responder status this way. In my app I had to use the makeFirstResponder instead. The only answer I got on Twitter in this regard was along the lines of &#8220;NSPageController is a bitch&#8221;.</p>
<h3>Editing Command Validation</h3>
<p>If a UIView can deal with the usual editing commands, like copy:, paste. et al then you can implement a canPerformAction:withSender: which depending on the selector passed in the action parameter can inform the system what actions are available. This is used by the system to only show menu items in UIMenuController that somebody can take care of.</p>
<p>On Mac the story is a bit more complicated. You&#8217;ll not find a canPerformAction method there. Instead you implement validateUserInterfaceItem which passes a generic object that tells you the action selector and an element tag.</p>

<div class="wp_codebox"><table><tr id="p713034"><td class="code" id="p7130code34"><pre class="objc" style="font-family:monospace;"><span style="color: #002200;">-</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">BOOL</span><span style="color: #002200;">&#41;</span>validateUserInterfaceItem<span style="color: #002200;">:</span><span style="color: #002200;">&#40;</span><span style="color: #a61390;">id</span> <span style="color: #002200;">&amp;</span>lt; <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Protocols/NSValidatedUserInterfaceItem_Protocol/"><span style="color: #2a6f76;">NSValidatedUserInterfaceItem</span></a> <span style="color: #002200;">&amp;</span>gt;<span style="color: #002200;">&#41;</span>anItem
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">SEL</span> action <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>anItem action<span style="color: #002200;">&#93;</span>;
	NSUInteger selectedZoneCount <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span><span style="color: #002200;">&#91;</span>self selectedHotZoneViews<span style="color: #002200;">&#93;</span> count<span style="color: #002200;">&#93;</span>;
&nbsp;
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>action <span style="color: #002200;">==</span> <span style="color: #a61390;">@selector</span><span style="color: #002200;">&#40;</span>selectAll<span style="color: #002200;">:</span><span style="color: #002200;">&#41;</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">&#91;</span>_hotZoneViews count<span style="color: #002200;">&#93;</span><span style="color: #002200;">&amp;</span>gt;selectedZoneCount<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #a61390;">return</span> <span style="color: #a61390;">YES</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
&nbsp;
	<span style="color: #a61390;">return</span> <span style="color: #a61390;">NO</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>You see, same mechanism, but on Mac this allows for many different kinds of NSValidatedUserInterfaceItems, be they menu items or something else. Apple probably decided on the different name to make it less confusing on the unsuspecting developer.</p>
<h3>Conclusion</h3>
<p>You can see the parallels in iOS and Mac everywhere you look. There are many classes that are identical on both OSes, but wherever there are different user interface paradigms you usually have an NS and UI class duality going on.</p>
<p>iOS is full of optimizations where you can Apple see cleaning up cruft that has gathered in AppKit classes and only putting the leanest and meanest parts into iOS. Thankfully with the success of this high octane approach the Mac platform apparently benefits from many &#8220;back to the Mac&#8221; tweaks under the hood.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=7130&amp;md5=a12e8a4af865f50fa18ce76b48b3b69c" 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/2012/10/assorted-observations/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F10%2Fassorted-observations%2F&amp;language=en_GB&amp;category=text&amp;title=Assorted+Observations&amp;description=While+I+am+developing+my+first+own+Mac+app+I%26%238217%3Bve+been+adding+to+this+blog+post+whenever+something+was+weird+to+me.+Or+simply+different.+You+can+definitely+see+in...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>CoreLocation Background Update Messaging</title>
		<link>http://www.cocoanetics.com/2012/06/corelocation-background-update-messaging/</link>
		<comments>http://www.cocoanetics.com/2012/06/corelocation-background-update-messaging/#comments</comments>
		<pubDate>Fri, 29 Jun 2012 10:29:25 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6652</guid>
		<description><![CDATA[Two years ago I put together revolutionary chart that detailed the flow of delegate messages when sending an app into background. This was even featured by Erica Sadun of TUAW because it for the first time visualized the whole process in a easy to understand way. Based on this chart Carl Brown from PDAgent made an addendum to deal with the special case of background region updates and sent it to me. To my shame I have to admit that it was sitting at the bottom of my inbox for 4 months now and it is only now that in my effort to reach Inbox Zero I am dealing with this and putting it up here for your viewing pleasure. This is the original flow as it was current with iOS 4 and I think it is also mostly true for iOS 5. And here is Carl&#8217;s CoreLocation addendum. I had originally planned to merge this flow chart with the original one, but it was not immediately obvious to me how I could achieve that in a visually pleasing way. Though maybe it would be smarter to keep them separate because they deal with different subsystems. Carl reported these findings from his experiments: The weird thing about the Core Location Delegate events is that you get application:didFinishLaunchingWithOptions: but it isn&#8217;t followed by applicationDidBecomeActive: or applicationWillEnterForeground: or applicationDidEnterBackground: &#8211; which is something I didn&#8217;t expect. The other odd thing is that if you double-tap the home button and use the task manager to Kill-9 the App, the next Core Location notification will launch the App again, but the App will not  re-appear in the recently used Apps list (as revealed by double-tapping the home button), so the user can&#8217;t kill the app again (at least not without launching it by hand first). So it becomes an effectively unkillable App (which makes your memory leaks way worse). So the most important info here seems to be that an app activated from a background location update neither becomes active nor enters any fore- or background. Which makes sense because we don&#8217;t want the app to pop to the front just because we have moved. It should be the user&#8217;s decision whether he would want to reopen the app. The OS will then make sure to take either the already running (or restarted) instance from the background or launch the app if it got terminated. Out of curiosity I still would love to merge both flow charts into one &#8220;ultimate&#8221; one. If you&#8217;re good with OmniGraffle then you can take a shot if you like to try, email me and I&#8217;ll send you the graffle files.]]></description>
				<content:encoded><![CDATA[<p>Two years ago I put together <a href="http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/">revolutionary chart</a> that detailed the flow of delegate messages when sending an app into background. This was even featured by Erica Sadun of TUAW because it for the first time visualized the whole process in a easy to understand way.</p>
<p>Based on this chart <a href="http://twitter.com/CarlBrwn">Carl Brown</a> from <a href="http://www.pdagent.com/">PDAgent</a> made an addendum to deal with the special case of background region updates and sent it to me. To my shame I have to admit that it was sitting at the bottom of my inbox for 4 months now and it is only now that in my effort to reach Inbox Zero I am dealing with this and putting it up here for your viewing pleasure.</p>
<p><span id="more-6652"></span></p>
<div id="more-6652"></div>
<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>
<p>This is the original flow as it was current with iOS 4 and I think it is also mostly true for iOS 5.</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/Bildschirmfoto-2012-03-05-um-5.26.29-PM.png"><img class="alignnone  wp-image-6054" title="UIApplication Delegate Messaging v1.3" src="http://i1.wp.com/www.cocoanetics.com/files/Bildschirmfoto-2012-03-05-um-5.26.29-PM.png?resize=599%2C819" alt="" data-recalc-dims="1" /></a></p>
<p>And here is Carl&#8217;s CoreLocation addendum. I had originally planned to merge this flow chart with the original one, but it was not immediately obvious to me how I could achieve that in a visually pleasing way.</p>
<p>Though maybe it would be smarter to keep them separate because they deal with different subsystems.</p>
<p><a href="http://i1.wp.com/www.cocoanetics.com/files/CoreLocation-Flowchart.png"><img class="alignnone size-full wp-image-6653" title="CoreLocation Flowchart" src="http://i1.wp.com/www.cocoanetics.com/files/CoreLocation-Flowchart.png?resize=573%2C657" alt="" data-recalc-dims="1" /></a></p>
<p>Carl reported these findings from his experiments:</p>
<blockquote><p>
The weird thing about the Core Location Delegate events is that you get application:didFinishLaunchingWithOptions: but it isn&#8217;t followed by applicationDidBecomeActive: or applicationWillEnterForeground: or applicationDidEnterBackground: &#8211; which is something I didn&#8217;t expect.</p>
<p>The other odd thing is that if you double-tap the home button and use the task manager to Kill-9 the App, the next Core Location notification will launch the App again, but the App will not  re-appear in the recently used Apps list (as revealed by double-tapping the home button), so the user can&#8217;t kill the app again (at least not without launching it by hand first). So it becomes an effectively unkillable App (which makes your memory leaks way worse).</p></blockquote>
<p>So the most important info here seems to be that an app activated from a background location update neither becomes active nor enters any fore- or background. Which makes sense because we don&#8217;t want the app to pop to the front just because we have moved. It should be the user&#8217;s decision whether he would want to reopen the app. The OS will then make sure to take either the already running (or restarted) instance from the background or launch the app if it got terminated.</p>
<p>Out of curiosity I still would love to merge both flow charts into one &#8220;ultimate&#8221; one. If you&#8217;re good with OmniGraffle then you can take a shot if you like to try, email me and I&#8217;ll send you the graffle files.</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6652&amp;md5=d602889d880eff09d30afe1b8b04bff5" 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/2012/06/corelocation-background-update-messaging/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F06%2Fcorelocation-background-update-messaging%2F&amp;language=en_GB&amp;category=text&amp;title=CoreLocation+Background+Update+Messaging&amp;description=Two+years+ago+I+put+together+revolutionary+chart+that+detailed+the+flow+of+delegate+messages+when+sending+an+app+into+background.+This+was+even+featured+by+Erica+Sadun+of+TUAW...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>Beware of NSString Optimizations</title>
		<link>http://www.cocoanetics.com/2012/03/beware-of-nsstring-optimizations/</link>
		<comments>http://www.cocoanetics.com/2012/03/beware-of-nsstring-optimizations/#comments</comments>
		<pubDate>Thu, 29 Mar 2012 17:03:27 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=6150</guid>
		<description><![CDATA[There are some scenarios where NSString acts as a class cluster internally to optimize handling of certain strings. One such case bit me today, and so I want to tell you about it. Class clusters work such that you think you are always dealing with just instances of NSString, but in reality the runtime goes and chooses different subclasses for certain tasks. You might have already seen some effects of this behavior when debugging and the debugger actually showing you something other than NSString as the type of a variable. Consider the following innocent splitting of tokens: NSString *text =@&#34;One,,two,three,&#34;; NSArray *components = &#91;text componentsSeparatedByString:@&#34;,&#34;&#93;; &#160; for &#40;NSString *oneString in components&#41; &#123; NSLog&#40;@&#34;'%@' = %@ %p&#34;, oneString, &#91;oneString class&#93;, oneString&#41;; &#125; What are the class types you expect to see for the individual components? NSString? Wrong. 'One' = __NSCFString 0x688e270 '' = __NSCFConstantString 0x1459cd8 'two' = __NSCFString 0x688e290 'three' = __NSCFString 0x6881890 '' = __NSCFConstantString 0x1459cd8 The NSCFStrings are actually toll-free bridging strings that can act as CFString in Core Foundation Land as well as NSString in Objective-C land. But note the NSCFConstantString! This is the kind of optimization that I fell prey to. Look at the memory address! The two empty strings are even one and the same object as you can see by glancing at the output memory address. Who would expect that? Not only is it a different class that you thought it would be, Objective-C also optimizes certain strings by folding them into certain other subclasses. Now for the example where this triggered a face-palm&#8230; It&#8217;s a Trap! In DTCoreText I added a convenience method that creates a HTML string from an attributed string. For this I am looping through the paragraphs and add P tags for each. NSArray *paragraphs = &#91;plainString componentsSeparatedByString:@&#34;\n&#34;&#93;; &#160; for &#40;NSString *oneParagraph in paragraphs&#41; &#123; NSRange paragraphRange = NSMakeRange&#40;location, &#91;oneParagraph length&#93;&#41;; &#160; // skip empty paragraph at end if &#40;oneParagraph == &#91;paragraphs lastObject&#93; &#38;&#38; !paragraphRange.length&#41; &#123; continue; &#125; ... &#125; Since the attributed string might have a \n at the end we don&#8217;t want to create an empty P. So I thought that it would be smart to compare the oneParagraph with the lastObject of the paragraphs array and if this was empty then skip it. BUT, I showed you above that an empty element is actually turned into a certain NSCFConstantString. This would mean that in this example every empty component would be equal to the empty last one and thus be skipped. Not what we wanted. Because of this optimization the lastObject method becomes useless to determine if oneParagraph is indeed the last one. We have change the slick fast enumeration to a classical for loop with a counter variable. for &#40;int i=0; i&#60;&#91;paragraphs count&#93;; i++&#41; &#123; NSString *oneParagraph = &#91;paragraphs objectAtIndex:i&#93;; NSRange paragraphRange = NSMakeRange&#40;location, &#91;oneParagraph length&#93;&#41;; &#160; // skip empty paragraph at the end if &#40;i==&#91;paragraphs count&#93;-1&#41; &#123; if &#40;!paragraphRange.length&#41; &#123; continue; &#125; &#125; ... &#125; It&#8217;s a bit clunkier, but now it is safe from this optimization. An alternative to this approach would be to still use fast enumeration, but increment a counter variable. But unfortunately there is no built-in method of knowing if one loop is the last one of the enumeration. So we still have to compare our counter with the array count. New or Improved? I wonder why this doesn&#8217;t confuse more people who are unaware of this optimization. Or is that something that was introduced in the later iOS SDKs? Well if you run the first code block on iOS 4.3 simulator you get a slightly different result. You still get both empty strings pointing to the same instance, but now the constant string is a &#8220;normal&#8221; NSCFString. So Apple apparently introduced the NSCFConstantString in iOS 5 to be able to optimized certain uses cases. Having a subclass allows them to override certain expensive operations like for example hardcoding the hash value. But apparently this folding of constant strings into single instances was around even before iOS 4 and so we have to be aware of this possibly wreaking havoc with our slick loop logic.]]></description>
				<content:encoded><![CDATA[<p>There are some scenarios where NSString acts as a class cluster internally to optimize handling of certain strings. One such case bit me today, and so I want to tell you about it.</p>
<p>Class clusters work such that you think you are always dealing with just instances of NSString, but in reality the runtime goes and chooses different subclasses for certain tasks. You might have already seen some effects of this behavior when debugging and the debugger actually showing you something other than NSString as the type of a variable.</p>
<p><span id="more-6150"></span></p>
<div id="more-6150"></div>
<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>
<p>Consider the following innocent splitting of tokens:</p>

<div class="wp_codebox"><table><tr id="p615046"><td class="code" id="p6150code46"><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>text <span style="color: #002200;">=</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;One,,two,three,&quot;</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>components <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>text componentsSeparatedByString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;,&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</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>oneString <span style="color: #a61390;">in</span> components<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	NSLog<span style="color: #002200;">&#40;</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;'%@' = %@ %p&quot;</span>, oneString, <span style="color: #002200;">&#91;</span>oneString class<span style="color: #002200;">&#93;</span>, oneString<span style="color: #002200;">&#41;</span>;
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>What are the class types you expect to see for the individual components? NSString? Wrong.</p>
<pre>
'One' = __NSCFString 0x688e270
'' = __NSCFConstantString 0x1459cd8
'two' = __NSCFString 0x688e290
'three' = __NSCFString 0x6881890
'' = __NSCFConstantString 0x1459cd8</pre>
<p>The NSCFStrings are actually toll-free bridging strings that can act as CFString in Core Foundation Land as well as NSString in Objective-C land. But note the NSCFConstantString!</p>
<p>This is the kind of optimization that I fell prey to. Look at the memory address! The two empty strings are even one and the same object as you can see by glancing at the output memory address. Who would expect that?</p>
<p>Not only is it a different class that you thought it would be, Objective-C also optimizes certain strings by folding them into certain other subclasses.</p>
<p>Now for the example where this triggered a face-palm&#8230;</p>
<h3>It&#8217;s a Trap!</h3>
<p>In DTCoreText I added a convenience method that creates a HTML string from an attributed string. For this I am looping through the paragraphs and add P tags for each.</p>

<div class="wp_codebox"><table><tr id="p615047"><td class="code" id="p6150code47"><pre class="objc" style="font-family:monospace;"><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>paragraphs <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>plainString componentsSeparatedByString<span style="color: #002200;">:</span><span style="color: #bf1d1a;">@</span><span style="color: #bf1d1a;">&quot;<span style="color: #2400d9;">\n</span>&quot;</span><span style="color: #002200;">&#93;</span>;
&nbsp;
<span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</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>oneParagraph <span style="color: #a61390;">in</span> paragraphs<span style="color: #002200;">&#41;</span>
<span style="color: #002200;">&#123;</span>
	<span style="color: #a61390;">NSRange</span> paragraphRange <span style="color: #002200;">=</span> NSMakeRange<span style="color: #002200;">&#40;</span>location, <span style="color: #002200;">&#91;</span>oneParagraph length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// skip empty paragraph at end</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>oneParagraph <span style="color: #002200;">==</span> <span style="color: #002200;">&#91;</span>paragraphs lastObject<span style="color: #002200;">&#93;</span> <span style="color: #002200;">&amp;&amp;</span> <span style="color: #002200;">!</span>paragraphRange.length<span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">continue</span>;
	<span style="color: #002200;">&#125;</span>
	...
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>Since the attributed string might have a \n at the end we don&#8217;t want to create an empty P. So I thought that it would be smart to compare the oneParagraph with the lastObject of the paragraphs array and if this was empty then skip it.</p>
<p>BUT, I showed you above that an empty element is actually turned into a certain NSCFConstantString. This would mean that in this example every empty component would be equal to the empty last one and thus be skipped. Not what we wanted.</p>
<p>Because of this optimization the lastObject method becomes useless to determine if oneParagraph is indeed the last one. We have change the slick fast enumeration to a classical for loop with a counter variable.</p>

<div class="wp_codebox"><table><tr id="p615048"><td class="code" id="p6150code48"><pre class="objc" style="font-family:monospace;"><span style="color: #a61390;">for</span> <span style="color: #002200;">&#40;</span><span style="color: #a61390;">int</span> i<span style="color: #002200;">=</span><span style="color: #2400d9;">0</span>; i&lt;<span style="color: #002200;">&#91;</span>paragraphs count<span style="color: #002200;">&#93;</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>oneParagraph <span style="color: #002200;">=</span> <span style="color: #002200;">&#91;</span>paragraphs objectAtIndex<span style="color: #002200;">:</span>i<span style="color: #002200;">&#93;</span>;
	<span style="color: #a61390;">NSRange</span> paragraphRange <span style="color: #002200;">=</span> NSMakeRange<span style="color: #002200;">&#40;</span>location, <span style="color: #002200;">&#91;</span>oneParagraph length<span style="color: #002200;">&#93;</span><span style="color: #002200;">&#41;</span>;
&nbsp;
	<span style="color: #11740a; font-style: italic;">// skip empty paragraph at the end</span>
	<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span>i<span style="color: #002200;">==</span><span style="color: #002200;">&#91;</span>paragraphs count<span style="color: #002200;">&#93;</span><span style="color: #002200;">-</span><span style="color: #2400d9;">1</span><span style="color: #002200;">&#41;</span>
	<span style="color: #002200;">&#123;</span>
		<span style="color: #a61390;">if</span> <span style="color: #002200;">&#40;</span><span style="color: #002200;">!</span>paragraphRange.length<span style="color: #002200;">&#41;</span>
		<span style="color: #002200;">&#123;</span>
			<span style="color: #a61390;">continue</span>;
		<span style="color: #002200;">&#125;</span>
	<span style="color: #002200;">&#125;</span>
	...
<span style="color: #002200;">&#125;</span></pre></td></tr></table></div>

<p>It&#8217;s a bit clunkier, but now it is safe from this optimization. An alternative to this approach would be to still use fast enumeration, but increment a counter variable. But unfortunately there is no built-in method of knowing if one loop is the last one of the enumeration. So we still have to compare our counter with the array count.</p>
<h3>New or Improved?</h3>
<p>I wonder why this doesn&#8217;t confuse more people who are unaware of this optimization. Or is that something that was introduced in the later iOS SDKs? Well if you run the first code block on iOS 4.3 simulator you get a slightly different result. </p>
<p>You still get both empty strings pointing to the same instance, but now the constant string is a &#8220;normal&#8221; NSCFString. So Apple apparently introduced the NSCFConstantString in iOS 5 to be able to optimized certain uses cases. Having a subclass allows them to override certain expensive operations like for example hardcoding the hash value. </p>
<p>But apparently this folding of constant strings into single instances was around even before iOS 4 and so we have to be aware of this possibly wreaking havoc with our slick loop logic. </p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=6150&amp;md5=d4cb91383074f0bf3e5a019b70dbde5c" 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/2012/03/beware-of-nsstring-optimizations/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F03%2Fbeware-of-nsstring-optimizations%2F&amp;language=en_GB&amp;category=text&amp;title=Beware+of+NSString+Optimizations&amp;description=There+are+some+scenarios+where+NSString+acts+as+a+class+cluster+internally+to+optimize+handling+of+certain+strings.+One+such+case+bit+me+today%2C+and+so+I+want+to+tell...&amp;tags=blog" type="text/html" />
	</item>
		<item>
		<title>ObjectiveSee Interview</title>
		<link>http://www.cocoanetics.com/2012/02/objectivesee-interview/</link>
		<comments>http://www.cocoanetics.com/2012/02/objectivesee-interview/#comments</comments>
		<pubDate>Tue, 14 Feb 2012 12:08:32 +0000</pubDate>
		<dc:creator>Drops</dc:creator>
				<category><![CDATA[Q&A]]></category>

		<guid isPermaLink="false">http://www.cocoanetics.com/?p=5963</guid>
		<description><![CDATA[ObjectiveSee is a web site dedicated to interviewing iOS developers. They use the format of a Q&#038;A and they have several intriguing people&#8217;s up already: Justin Williams, Nathan Spindel, Keith Blount, Whitney Young, &#8230; oh and ME!]]></description>
				<content:encoded><![CDATA[<p><a href="http://www.objectivesee.com/">ObjectiveSee</a> is a web site dedicated to interviewing iOS developers. They use the format of a Q&#038;A and they have several intriguing people&#8217;s up already: <a href="http://www.objectivesee.com/justin.williams.html">Justin Williams</a>, <a href="http://www.objectivesee.com/nathan.spindel.html">Nathan Spindel</a>, <a href="http://www.objectivesee.com/keith.blount.html">Keith Blount</a>, <a href="http://www.objectivesee.com/whitney.young.html">Whitney Young</a>, &#8230; oh and <a href="http://www.objectivesee.com/oliver.drobnik.html">ME</a>!</p>
 <p><a href="http://www.cocoanetics.com/?flattrss_redirect&amp;id=5963&amp;md5=fb1eeb360eca85ac1a04ef0dd4180cc5" 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/2012/02/objectivesee-interview/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2012%2F02%2Fobjectivesee-interview%2F&amp;language=en_GB&amp;category=text&amp;title=ObjectiveSee+Interview&amp;description=ObjectiveSee+is+a+web+site+dedicated+to+interviewing+iOS+developers.+They+use+the+format+of+a+Q%26%23038%3BA+and+they+have+several+intriguing+people%26%238217%3Bs+up+already%3A+Justin+Williams%2C+Nathan+Spindel%2C+Keith...&amp;tags=blog" type="text/html" />
	</item>
		<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! 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[<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="p575154"><td class="code" id="p5751code54"><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 id="more-5751"></div>
<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>
<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="p575155"><td class="code" id="p5751code55"><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>5</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fios-5-breaking-nsdateformatter%2F&amp;language=en_GB&amp;category=text&amp;title=iOS+5+Breaking+NSDateFormatter%3F&amp;description=Robert+Meraner+asks%3A+%26%238220%3BDo+you+have+any+idea+why+this+code+works+in+iOS+4.3%2C+but+no+longer+under+iOS+5%3F+Googling+it+seems+to+turn+up+some+ideas%2C+but...&amp;tags=blog" 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. 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 = 1 &#60;&#60; 0, UIViewAnimationOptionAllowUserInteraction = [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5738"></div>
<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>
<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="p573865"><td class="code" id="p5738code65"><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="p573866"><td class="code" id="p5738code66"><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="p573867"><td class="code" id="p5738code67"><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="p573868"><td class="code" id="p5738code68"><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="p573869"><td class="code" id="p5738code69"><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="p573870"><td class="code" id="p5738code70"><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="p573871"><td class="code" id="p5738code71"><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>5</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fbit-masks%2F&amp;language=en_GB&amp;category=text&amp;title=Bit+Masks&amp;description=Joseph+Collins+asks%3A+How+do+you+decipher+a+bit+mask+from+an+argument+which+logically+OR%26%238217%3Bd+multiple+values+together%3F+Enum+uses+bit+shifting.+This+question+came+to+me+while+looking...&amp;tags=blog" 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. 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 the parameter is to be textColor [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5708"></div>
<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>
<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="p570883"><td class="code" id="p5708code83"><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="p570884"><td class="code" id="p5708code84"><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="p570885"><td class="code" id="p5708code85"><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="p570886"><td class="code" id="p5708code86"><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" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F12%2Fcoding-style%2F&amp;language=en_GB&amp;category=text&amp;title=Coding+Style&amp;description=Dany+asked%3A+I%26%238217%3Bm+looking+at+your+%28nice%29+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%2C+and...&amp;tags=blog" 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; Update: I resurrected the Cocoanetics Podcast! Subscribe to it on iTunes or add the RSS feed to your favorite podcasting app or listen to the shows right on this website. 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). 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[<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><strong>Update:</strong> I resurrected the Cocoanetics Podcast! Subscribe to it <a href="http://itunes.apple.com/us/podcast/cocoanetics/id341821932">on iTunes</a> or add the <a href="http://www.cocoanetics.com/podcast">RSS feed</a> to your favorite podcasting app or listen to the shows <a href="http://www.cocoanetics.com/category/podcast">right on this website</a>.</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 id="more-5401"></div>
<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>
<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>7</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F09%2Fpodcasts-for-ios-developers%2F&amp;language=en_GB&amp;category=text&amp;title=Podcasts+for+iOS+Developers&amp;description=I+once+dabbled+a+bit+in+podcasting+myself+with+the+Dr.+Touch+%2F+Cocoanetics+podcast%2C+but+I+decided+that+I+am+not+going+to+continue+that+on+my+own.+I...&amp;tags=blog" 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. 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 purpose. Please refer to DemoSnippetsViewController.m to [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5373"></div>
<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>
<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/DTCoreText">hosted on GitHub</a>. If you find problems then please <a href="https://github.com/Cocoanetics/DTCoreText/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="http://www.cocoanetics.com/order/?product=DTCoreText%20Non-Attribution%20License">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>26</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F08%2Fnsattributedstringhtml-qa%2F&amp;language=en_GB&amp;category=text&amp;title=NSAttributedString%2BHTML+Q%26%23038%3BA&amp;description=Over+the+past+few+months+I+have+received+questions+about+NSAttributedString%2BHTML+and+Rich+Text+Editing.+Here+are+the+Frequently+Asked+Questions.+I+generally+abbreviate+NSAttributedString%2BHTML+as+NSAS%2BHTML.%C2%A0If+your+question+or...&amp;tags=blog" 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. 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 want because it looks weird. So [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5347"></div>
<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>
<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://i2.wp.com/www.cocoanetics.com/files/StGyg.png"><img class="alignnone size-medium wp-image-5348" title="Faded out top and bottom tableview cells" src="http://i2.wp.com/www.cocoanetics.com/files/StGyg.png?resize=193%2C300" alt="" data-recalc-dims="1" /></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="p534795"><td class="code" id="p5347code95"><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="p534796"><td class="code" id="p5347code96"><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="p534797"><td class="code" id="p5347code97"><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://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-9.48.16-AM.png"><img src="http://i2.wp.com/www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-9.48.16-AM.png?resize=161%2C300" alt="" title="Masked Table View" class="alignnone size-medium wp-image-5349" data-recalc-dims="1" /></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="p534798"><td class="code" id="p5347code98"><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://i0.wp.com/www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-10.18.54-AM.png"><img src="http://i0.wp.com/www.cocoanetics.com/files/Screen-Shot-2011-08-26-at-10.18.54-AM.png?resize=162%2C300" alt="" title="Tableview with fading not affecting the scroll bar" class="alignnone size-medium wp-image-5356" data-recalc-dims="1" /></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>12</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F08%2Fadding-fading-gradients-to-uitableview%2F&amp;language=en_GB&amp;category=text&amp;title=Adding+Fading+Gradients+to+UITableView&amp;description=Jason+Jardim+asked+%284+Months+ago%29%3A+This+is+just+a+screen+shot+I+found+with+someone+posting+a+similar+question.+%C2%A0I+am+trying+to+fade+out+he+top%2F+bottom+cells...&amp;tags=blog" 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. 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 license to kill &#8230; your device. [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5168"></div>
<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>
<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://i2.wp.com/www.cocoanetics.com/files/UK-Train-Times.png"><img class="alignnone size-full wp-image-5169" title="UK-Train-Times" src="http://i2.wp.com/www.cocoanetics.com/files/UK-Train-Times.png?resize=707%2C114" alt="" data-recalc-dims="1" /></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" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F06%2Fsafe-to-install-ios5%2F&amp;language=en_GB&amp;category=text&amp;title=Is+it+safe+to+install+iOS+5+on+your+everyday+iPhone%3F&amp;description=On+the+heels+of+the+iOS+5+announcement+I+started+getting+a+multitude+of+e-mails+asking+more+or+less+the+same+thing%3A+I+have+only+my+everyday+iPhone+for+developing%2C...&amp;tags=blog" 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.  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 getting AT&#38;T prepaid data on my [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5121"></div>
<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>
<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://i1.wp.com/www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' data-recalc-dims="1" /> </li>
</ol>
<p><a href="http://i2.wp.com/www.cocoanetics.com/files/IMG_06541.png"><img class="alignnone size-full wp-image-5122" title="AT&amp;T APN Settings" src="http://i2.wp.com/www.cocoanetics.com/files/IMG_06541.png?resize=384%2C576" alt="" data-recalc-dims="1" /></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://i1.wp.com/www.cocoanetics.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' data-recalc-dims="1" /> </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>22</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F05%2Fiphone-3g-data-usa-truth-fiction%2F&amp;language=en_GB&amp;category=text&amp;title=Prepaid+3G+Data+for+Visitors+to+the+USA+%26%238211%3B+Truth+and+Fiction&amp;description=As+a+fellow+iOS+Developer+you+might+find+yourself+in+San+Francisco+for+WWDC+or+maybe+on+assignment.+If+you%26%238217%3Bre+like+me+then+you+cannot+survive+with+a+modicum+of...&amp;tags=blog" 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. 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 be a waste of the client&#8217;s [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5112"></div>
<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>
<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" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F05%2Ftons-of-changes%2F&amp;language=en_GB&amp;category=text&amp;title=Tons+of+Changes&amp;description=Devin+Snipes+asks%3A+I%26%238217%3Bve+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...&amp;tags=blog" 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. 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 lists of products in XML, for [...]]]></description>
				<content:encoded><![CDATA[<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 id="more-5082"></div>
<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>
<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" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F05%2Fwhat-impact-will-new-web-technologies-have-on-ios-developers%2F&amp;language=en_GB&amp;category=text&amp;title=What+Impact+will+new+Web-Technologies+have+on+iOS+Developers%3F&amp;description=Jamar+Parris+asks%3A+I%26%238217%3Bve+really+been+contemplating+whether+to+focus+my+efforts+on+one+versus+the+other+as+I%26%238217%3Bm+still+new+to+both+technologies.+What+impact+do+you+think+will...&amp;tags=blog" 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. 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[<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 id="more-5046"></div>
<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>
<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://i2.wp.com/www.cocoanetics.com/files/top100_comparison.jpg"><img class="size-large wp-image-5047 alignnone" title="Top100 Comparison iPhone/iPad" src="http://i2.wp.com/www.cocoanetics.com/files/top100_comparison.jpg?resize=207%2C1024" alt="" data-recalc-dims="1" /></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>8</slash:comments>
		<atom:link rel="payment" title="Flattr this!" href="https://flattr.com/submit/auto?user_id=dr_touch&amp;url=http%3A%2F%2Fwww.cocoanetics.com%2F2011%2F05%2Fto-universal-or-not%2F&amp;language=en_GB&amp;category=text&amp;title=To+Universal+or+Not&amp;description=Daniel+Wood+asked%3A+Considering+making+a+Blockees+universal.+What+are+people%26%238217%3Bs+thoughts+on+universal+apps%3F+Good+for+users%2C+but+splits+sales+between+devices.+My+first+gut+response+was%2C+that+IMHO...&amp;tags=blog" type="text/html" />
	</item>
	</channel>
</rss>
