<?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>markbetz.net &#187; Programming</title>
	<atom:link href="http://www.markbetz.net/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.markbetz.net</link>
	<description>Completely unknown to millions</description>
	<lastBuildDate>Sun, 29 Jan 2012 19:10:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Creating Image Thumbs with TransformedBitmap and ScaleTransform</title>
		<link>http://www.markbetz.net/2011/05/31/creating-image-thumbs-with-transformedbitmap-and-scaletransform/</link>
		<comments>http://www.markbetz.net/2011/05/31/creating-image-thumbs-with-transformedbitmap-and-scaletransform/#comments</comments>
		<pubDate>Tue, 31 May 2011 04:09:50 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1353</guid>
		<description><![CDATA[With WPF and the classes in the System.Windows.Media.Imaging namespace, creating thumbnails from source images has never been easier to do. The code fragment below illustrates how to create thumbnails from a source image using TransformedBitmap and ScaleTransform. You can use the same technique to apply other types of transforms to an image, such as rotations. [...]]]></description>
			<content:encoded><![CDATA[<p>With WPF and the classes in the System.Windows.Media.Imaging namespace, creating thumbnails from source images has never been easier to do. The code fragment below illustrates how to create thumbnails from a source image using TransformedBitmap and ScaleTransform. You can use the same technique to apply other types of transforms to an image, such as rotations.</p>
<p>Let&#8217;s first define our method signature&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
using System.Windows.Media;
using System.Windows.Media.Imaging;
void CreateThumbnail(string sourceImage, string outputImage, int width, int height)
</pre>
<p>The next thing to do is to get our source image into a BitmapSource&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">BitmapSource imageSource = BitmapFrame.Create(new Uri(sourceImage));</pre>
<p>The class that defines the transformation to be applied to the image is ScaleTransform. We need to create one of these and set the scaling factor to be applied to the width and height&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
ScaleTransform st = new ScaleTransform();
st.ScaleX = (double)width / (double)imageSource.PixelWidth;
st.ScaleY = (double)height / (double)imageSource.PixelHeight;
</pre>
<p>With the transform defined, we need a TransformedBitmap to apply it to&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">TransformedBitmap tb = new TransformedBitmap(imageSource, st);</pre>
<p>The TransformedBitmap now contains the bitmap after the scaling transform has been applied. The only thing left to do now is write it to disk. In the process we&#8217;ll add some metadata just to show how that is done as well&#8230;</p>
<pre class="brush: csharp; title: ; notranslate">
BitmapMetadata thumbMeta = new BitmapMetadata(&quot;jpg&quot;);
thumbMeta.Title = &quot;thumbnail&quot;;
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.QualityLevel = 100;
encoder.Frames.Add(BitmapFrame.Create(tb, null, thumbMeta, null));
using (FileStream stream = new FileStream(outputImage, FileMode.Create))
{
    encoder.Save(stream);
    stream.Close();
}
</pre>
<p>And that&#8217;s pretty much all there is to it. As I mentioned above you can use this exact same approach to apply any of the other transform classes in the System.Windows.Media namespace. These are all derived from System.Windows.Media.Transform, and in addition to ScaleTransform they include: RotateTransform, SkewTransform, TranslateTransform, and MatrixTransform.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2011/05/31/creating-image-thumbs-with-transformedbitmap-and-scaletransform/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SmoothGen 0.9</title>
		<link>http://www.markbetz.net/2011/05/30/smoothgen-0-9/</link>
		<comments>http://www.markbetz.net/2011/05/30/smoothgen-0-9/#comments</comments>
		<pubDate>Tue, 31 May 2011 03:34:33 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1348</guid>
		<description><![CDATA[Recently I went hunting for an open source slideshow tool that would work with my WordPress installation. I found lots of alternatives, but most of them interacted with the WordPress database in one way or another, typically by requiring the slideshow to be defined by attaching pics from the media library to a post, and [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I went hunting for an open source slideshow tool that would work with my WordPress installation. I found lots of alternatives, but most of them interacted with the WordPress database in one way or another, typically by requiring the slideshow to be defined by attaching pics from the media library to a post, and then annotating the post with some tag that would kick off the slideshow.</p>
<p>There&#8217;s nothing wrong with the built-in media library, as far as it goes, but it isn&#8217;t really suited for managing large numbers of images sorted into categories, i.e. 30 images for one slideshow, 20 for another, etc. There are some plugins that improve on it, but this was all more complicated than I wanted it to be. All I wanted was to be able to prepare a folder of images and have the slideshow drive off of that. Fortunately I discovered exactly what I needed in JonDesign&#8217;s <a href="http://smoothgallery.jondesign.net/" target="_blank">SmoothGallery 2.0</a>.</p>
<p>SmoothGallery is a MooTools-based slideshow driver that works off of an HTML document or fragment that describes all the images in the slideshow, as well as the metadata associated with each image (title, description, etc.). The nice thing about this is that it is search engine friendly, and self-contained. The downside is that you have to prepare the HTML document that describes the slideshow. I&#8217;m pretty lazy, and didn&#8217;t relish the idea of manually adding image elements for 50 slideshow images. So I wrote a tool to do it for me.</p>
<p>SmoothGen is a simple console program that takes as input a folder of images, and outputs a complete HTML document describing the slideshow. It supports all of the options available in SmoothGallery, as well as some additional features such as alternative thumbnail sizes, changing the height of the info pane, and importing title/description fields from image metadata. It was written to work with SmoothGallery 2.0, and requires the .Net framework version 4 to run. The source is included, so you should be able to rebuild it for earlier versions of the framework if you need to. If you have any questions that aren&#8217;t answered in the documentation, feel free to drop a comment here.</p>
<p><a href="http://www.markbetz.net/misc/sg/SmoothGen.zip">Download SmoothGen 0.9</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2011/05/30/smoothgen-0-9/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Config Transforms in Visual Studio 2010</title>
		<link>http://www.markbetz.net/2011/04/26/simple-config-transforms-in-visual-studio-2010/</link>
		<comments>http://www.markbetz.net/2011/04/26/simple-config-transforms-in-visual-studio-2010/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 03:16:32 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1250</guid>
		<description><![CDATA[If you&#8217;ve worked on the Microsoft ASP.NET platform for any length of time, in an environment where you had to manage deployment of your application across multiple servers, then you&#8217;ve probably stared at .config files until your head pounds. In the past we often managed this by keeping multiple copies of each .config and using [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve worked on the Microsoft ASP.NET platform for any length of time, in an environment where you had to manage deployment of your application across multiple servers, then you&#8217;ve probably stared at .config files until your head pounds. In the past we often managed this by keeping multiple copies of each .config and using pre-build events to copy the right one to the right place based on the active configuration. Recently my colleague Erez clued me in to the fact that Microsoft had stepped up and offered a solution in Visual Studio 2010 called &#8220;config transformations.&#8221;</p>
<p>Config transformations are essentially a set of rules, similar to an XSLT in intent, if not in syntax, that replace or transform the content of specific nodes in the .config XML when the site is published. The full capability is quite powerful, but I am going to ignore 90% of it here. If you want to understand the whole thing there is a <a href="http://blogs.msdn.com/b/webdevtools/archive/2009/05/04/web-deployment-web-config-transformation.aspx" target="_blank">useful post</a> on the Visual Web Team Developer blog. It&#8217;s very interesting stuff, but my favorite line was the one that began, &#8220;Simplest Approach: If you do not mind replicating the entire web.config file in web.staging.config then you can certainly do so&#8230;&#8221; Bingo! I may take advantage of all the neato matching rules later. For now I&#8217;m happy if I can achieve what we do now without requiring script to be created and maintained in a pre-build event.</p>
<p>Fortunately this is dead simple to do. The first step will be to create the transforms. The idea is that you have a base configuration named web.config, and one or more transforms that are applied to it when publishing under specific configurations. If you&#8217;re starting with a new web app then transforms for the default &#8220;Debug&#8221; and &#8220;Release&#8221; configurations will be created for you. You will find them as file nodes under web.config in the Solution Explorer, similar to the way code behind and designer files are handled. If, like us, you have a solution that predates VS2010 and want to start using config transforms, here&#8217;s what you do:</p>
<p>First, make sure you have your configurations set up. We usually have local (Dev), Test, and Production configurations on web apps. Right-click the existing web.config file in Solution Explorer and click &#8220;Add Config Transforms.&#8221;</p>
<p><img class="ngg-singlepic ngg-center" src="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/config_example2_0.png" alt="config_example2" /></p>
<p>Visual Studio will add transforms for any existing configuration that doesn&#8217;t already have one. In this simple example the result is two new files: Web.Debug.config and Web.Release.config. Here&#8217;s what it should look like after you finish:</p>
<p><img class="ngg-singlepic ngg-center" src="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/config_example3.png" alt="config_example3" /></p>
<p>The next step is to delete one of them. Why? Well, recall that these are transforms. They change the base .config so that it will work in another environment. Which config doesn&#8217;t need to be transformed? The web.config that you use to run locally. What I like to do is modify the existing, or default Web.config so that it is set up to work in local debug situations, and then use transforms to modify it when the app runs in other environments. So in the example above you would get rid of Web.Debug.config, modify Web.config for local debugging, and modify the transform in Web.Release.config to work in the production environment. Here&#8217;s a simple Web.config that I will use to illustrate the rest of the example:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
	&lt;appSettings&gt;
		&lt;add key=&quot;baseUrl&quot; value=&quot;http://localhost:32767&quot; /&gt;
	&lt;/appSettings&gt;
	&lt;connectionStrings&gt;
		&lt;add name=&quot;SiteDB&quot; connectionString=&quot;server=localhost;database=SiteDB;uid=user;pwd=password&quot;/&gt;
	&lt;/connectionStrings&gt;
&lt;/configuration&gt;
</pre>
<p>As you can see this is set up for local debugging. Now for the release config. If you open up one of the transform files in the editor you&#8217;ll notice that it just contains an empty configuration node, along with some additional namespace information. Since we&#8217;re taking the simple route and swapping the entire file, the next thing to do is copy the contents of the configuration node from Web.Config to Web.Release.Config and modify it to work in the release environment. We also have to add the attribute that tells the transform tool to swap out the entire configuration node. Here&#8221;s what the completed file looks like:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration xmlns:xdt=&quot;http://schemas.microsoft.com/XML-Document-Transform&quot; xdt:Transform=&quot;Replace&quot;&gt;
	&lt;appSettings&gt;
		&lt;add key=&quot;baseUrl&quot; value=&quot;http://www.mysite.com&quot; /&gt;
	&lt;/appSettings&gt;
	&lt;connectionStrings&gt;
		&lt;add name=&quot;SiteDB&quot; connectionString=&quot;server=proddbserver;database=SiteDB;uid=user;pwd=password&quot;/&gt;
	&lt;/connectionStrings&gt;
&lt;/configuration&gt;
</pre>
<p>Note the additional namespace attribute on the configuration node. That namespace contains the element and attribute definitions used to define the transformation rules. The template will add this for you when it creates the files. The second attribute on the configuration node is one we need to add manually. The attribute <strong>xdt:Transform=&#8221;replace&#8221;</strong> tells the tool to replace the entire contents of a node in the base config with the contents of the same node in the transform. Since we placed this rule on the root configuration node, the entire contents of the config will get pasted in when we publish.</p>
<p>And that&#8217;s pretty much it. Once you have this set up the transform will be applied when you publish the site under a named configuration for which a transform exists. One thing to note, which confused me for a couple of minutes, is that the transforms are not applied on a simple local build. If you want the transform to run without publishing you apparently have to add a custom task to your project file and then call it from an event. This decision doesn&#8217;t really make sense to me, but I haven&#8217;t taken the time to research it and see why they did it this way. Fortunately all my local builds are under my &#8220;Dev&#8221; configuration, which is handled by the base Web.config, so this doesn&#8217;t really cause me an issue. When I publish to test or production the transforms run, and everything works great.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2011/04/26/simple-config-transforms-in-visual-studio-2010/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Sliding Number Puzzle in JQuery</title>
		<link>http://www.markbetz.net/2011/04/14/a-sliding-number-puzzle-in-jquery/</link>
		<comments>http://www.markbetz.net/2011/04/14/a-sliding-number-puzzle-in-jquery/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 05:13:44 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1244</guid>
		<description><![CDATA[I&#8217;ve never really been a huge javascript fan. I learned to program using an interpreted, weakly-typed language called BASIC. It was fun, interactive, stream-of-consciousness, creative, and a great way to learn the, um, basics. It was also pretty hard to write big, complicated programs in it. I happened to learn the language back in the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve never really been a huge javascript fan. I learned to program using an interpreted, weakly-typed language called BASIC. It was fun, interactive, stream-of-consciousness, creative, and a great way to learn the, um, basics. It was also pretty hard to write big, complicated programs in it. I happened to learn the language back in the mid-70&#8242;s on an HP3000 mainframe. We had access to two CRT and two teletype terminals. I recall that there was a pecking order in the student computer room, and it was awhile before I worked my way up to getting time on a CRT. Up to that point I had to print out every run and save my programs on punch tape, so my efforts were somewhat confined. Once on the CRT I began to scale up, and one of my aspirations was to write a space game. But this was pre-procedural BASIC, all gotos and gosubs, and it was only a few ten thousands of lines long when its complexity outstripped my structural abilities and it collapsed into a heap.</p>
<p>I still have a prejudice in favor of strongly-typed, compiled languages, but I also think scripting is the future of the bulk of development. And it&#8217;s still fun. Working with javascript or php today is the equivalent, for me, of loading up the BASIC interpreter and making stuff happen. It&#8217;s relaxing after spending my professional day wrangling huge .net solutions across multiple servers and staring at .configs until my eyes water. And just as I did back in the day, I still turn to games when I want to learn something new. They&#8217;re fun to program and they cover pretty much every aspect of a language. When I wanted to learn Silverlight I wrote <a href="http://www.markbetz.net/sl/gmemory" target="_blank">GMemory</a>, a deservedly unheralded accomplishment, but still fun to do. Recently I desired to get up to speed on JQuery, so once again I created a <a href="http://www.markbetz.net/jq/numberPuzzle" target="_blank">dumb game</a>.</p>
<p>The sliding number puzzle has been around since the mid-nineteenth century. I remember my parents bought them for us to play with on long family car trips, which probably explains a lot about me. They come in various sizes, with the most standard being the <a href="http://en.wikipedia.org/wiki/Fifteen_puzzle" target="_blank">fifteen-puzzle</a>, so named because it is a 4 x 4 grid of sliding tiles with one empty spot. I didn&#8217;t know this when I started working on mine, so mine is a 35-puzzle, implemented entirely in javascript using JQuery. JQuery is brilliant, for a lot of reasons, but that&#8217;s another post. Suffice it to say that it was a lot of fun to work with, and the puzzle itself is interesting. It turns out that the mathematics of the sliding number puzzle have been studied for a long time, and it has proven to be an interesting problem for computer scientists as well, in terms of its inherent properties and the challenges of solving it.</p>
<p>However, before you spend much time trying to solve mine, I should mention that half the puzzles it generates cannot be solved. This is some mathematical property of the puzzle itself which was discovered by some guys named Johnson and Story back in 1879. Unfortunately you can&#8217;t tell if you are working on an unsolvable puzzle unto you get to the last number. Muwaahahahahaha. There&#8217;s a test to detect an unsolvable configuration, but I haven&#8217;t implemented it yet. I also haven&#8217;t implemented a solver. There are both search-based and pattern-based approaches to solving the sliding number puzzle, and I wanted to implement one and animate the solution, but I haven&#8217;t had the time. If you feel like trying, there&#8217;s a link to download the source files on the demo page.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2011/04/14/a-sliding-number-puzzle-in-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iOS Diary: 5 Tips for Leak-free Apps</title>
		<link>http://www.markbetz.net/2010/10/24/ios-diary-5-tips-for-leak-free-apps/</link>
		<comments>http://www.markbetz.net/2010/10/24/ios-diary-5-tips-for-leak-free-apps/#comments</comments>
		<pubDate>Mon, 25 Oct 2010 01:53:28 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1185</guid>
		<description><![CDATA[So you want to do some iOS development, but you&#8217;ve heard that memory management is a chore? Have no fear. All you have to do is keep track of a reference count on every object in your application, making sure that when the last live pointer to each dies, the object has a ref count [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/thinking_about_ios2.jpg" title="" class="thickbox" rel="singlepic547" >
	<img class="ngg-singlepic ngg-left" src="http://www.markbetz.net/wp-content/gallery/cache/547__151x151_thinking_about_ios2.jpg" alt="thinking_about_ios2" title="thinking_about_ios2" />
</a>

<p>So you want to do some iOS development, but you&#8217;ve heard that memory management is a chore? Have no fear. All you have to do is keep track of a reference count on every object in your application, making sure that when the last live pointer to each dies, the object has a ref count of 0 so that it can be deallocated. Ok, so maybe it does suck. If you&#8217;re used to modern tools like C# or Java then this world is a real throwback. Fortunately Apple provides some awesome tools for tracking down problems with leaks, and if you follow the right conventions you too can keep your objects from lying around and growing moldy. Since I just went through my first iOS project, and am now an expert, here are five things I&#8217;ve learned about iOS memory management:</p>
<h4>1. Know the difference between alloc/init and with/by/from/of methods.</h4>
<p>The alloc and init methods are the standard means for creating an object on the heap. Some common forms are:</p>
<pre class="brush: cpp; title: ; notranslate">
MyObject *anObject = [[MyObject alloc] init];
MyObject *anObject = [[MyObject alloc] initWithSomeText:text];
MyObject *anObject = [[MyObject alloc] initWithColor:[UIColor blueColor]];
</pre>
<p>One thing that is true about all forms of alloc/init is that they return an object with a reference count of 1. You own that object, and are responsible for releasing it. By contrast what I called the with/by/from/of methods are factory methods that you call to get an object. A few examples you might have seen:</p>
<pre class="brush: cpp; title: ; notranslate">
NSString *myString = [NSString stringWithFormat:@&quot;%@&quot;, someObject];
NSString *myString = [anotherString stringByAppendingString:aThirdString];
UIFont* aFont = [UIFont boldSystemFontOfSize:17];
</pre>
<p>Most methods of this form return an autoreleased object. Unless you retain the result then it&#8217;s going to be released and deallocated when the next event loop runs. So when do you want to own an object, and when do you want one that is autoreleased? Consider a scenario where you&#8217;re passed a string in a callback, and are going to assign it to a property and keep it around. By convention, when you are passed an object in an argument to a method call you don&#8217;t own it. You don&#8217;t know what the caller is going to do to that object after the method returns. So you want to copy it to your property. Here is one way I&#8217;ve seen that done:</p>
<pre class="brush: cpp; title: ; notranslate">
@interface MyClass {
}
@property (nonatomic, retain) NSString *myProperty;
@end

@implementation MyClass
@synthesize myProperty;

-(void)somethingSureMessedUp:(NSString *)reason {
    self.myProperty = [[NSString alloc] initWithString:reason];
}
@end
</pre>
<p>The question is: will that code leak? The answer is yes, it will. The initWithString method returns a new object with a reference count of 1. It is then assigned to a retained property. When an object is assigned to a retained property two things happen: the existing value is released, and the new value is retained. So the string now has a reference count of 2, and even if you follow my tip on releasing retained properties it will still leak. The alternative is the factory method:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)somethingSureMessedUp:(NSString *)reason {
    self.myProperty = [NSString stringWithString:reason];
}
</pre>
<p>The stringWithString method also returns an object with a reference count of 1, so when we assign it to the retained property it still has a reference count of 2. But before the method returned our shiny new string it called autorelease on it. So when we return from this method and the autorelease pool gets processed this sting is getting a release call, and the reference count will be back to 1. Result: no leak.</p>
<p>So, when do you use init/alloc? Sometimes there isn&#8217;t a convenient factory method and you don&#8217;t have a choice. In those cases you may want to follow the pattern in Tip 2. In other scenarios you may have an interface component, or a collection, whose lifetime is the same as the containing class. In those cases feel free to call init/alloc and then release the reference in your container&#8217;s dealloc.</p>
<h4>2. Autorelease what you don&#8217;t retain</h4>
<p>This is the corollary to Tip 1: if you write a method that produces an object, and you don&#8217;t specifically keep a reference to that object and ensure that it is released on dealloc, then autorelease it before letting the reference go. In the context of the example above, if there was no convenient factory method that returned an autoreleased object you could follow another common pattern:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)yourDaughterTookTheCar:(NSString *)reason {
    self.myProperty = [[[NSString alloc] initWithString:reason] autorelease];
}
</pre>
<p>In this case you&#8217;re doing the same thing that the factory method does internally. Your autorelease will balance out the retain that the property setter will do, and nothing will leak, assuming you follow Tip 5.</p>
<h4>3. Use properties</h4>
<p>Sure, everyone uses properties when they want to make something available to another class, but what about when you just have some internal objects to keep track of? In general, unless a reference has exactly the same lifetime as its container class, i.e. the object it points to is created when the container is created, and deallocated when the container is deallocated, then it makes more sense to keep it in a property than to use an ivar. This is especially true if the reference is going to point to different objects over the lifecycle of the program.</p>
<p>Retained properties retain and release their objects, so assigning a new value to one automatically releases the previous value. This behavior makes it much easier to keep the reference counts of objects with transient lifetimes balanced. The follow-up rule to this one is Tip 4.</p>
<h4>4. Always use property access syntax to access properties</h4>
<p>I wrote a <a href="http://www.markbetz.net/2010/09/19/ios-diary-when-is-a-property-access-not-a-property-access/" target="_self">short post</a> on this one a few weeks ago. Properties are backed up by ivars, and ivars are accessible within the implementation of the class that declares them. It&#8217;s all too easy to do this:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)sheBetterBringItBack:(NSString *)reason {
    myProperty = [NSString stringWithString:reason];
}
</pre>
<p>Outside callers can&#8217;t do this, because they can&#8217;t see the ivar (unless its public, and it shouldn&#8217;t be) and have to use property access syntax. Although you can get away with this inside the declaring class, its either a leak or a crash waiting to happen. The problem is that this notation (leaving out &#8220;self.&#8221;) bypasses the property setter completely. There is no operator overloading in C, and C is all Objective-C is in the end. The only way to make sure that you call the setter and properly retain the object is to use . syntax to reference the name. Of course you could do this:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)somethingSureMessedUp:(NSString *)reason {
    myProperty = [[NSString stringWithString:reason] retain];
}
</pre>
<p>But why would you? You&#8217;re just doing an end-run around the property mechanism, and you might as well work with it rather than against it. Declaring and using properties correctly can help a lot with the management of object reference counts. My last tip involves what to do with properties at the end of the world.</p>
<h4>5. Release retained properties in dealloc</h4>
<p>This one might seem like a no-brainer, but it has caught me a couple of times (which doesn&#8217;t prove that it isn&#8217;t a no-brainer), especially when adding new retained properties to an existing class. The property mechanism only comes into play when a property is set. At the end of the world, when your container object&#8217;s dealloc method is called, remember to go through your retained properties and release any that aren&#8217;t nil. You can either release them explicitly, or by setting them to nil, but either way they remain your responsibility.</p>
<p>And that&#8217;s it, except for one last bonus tip: learn to use the Instruments framework in XCode to profile your memory usage. Apple is pretty strict about app behavior, and leaks can get your work rejected. The leak and allocations analysis tools are really very impressive, and remind me of using Bounds Checker back in the day. They are too big a topic to tack onto the end of this post, but Apple&#8217;s developer site has <a href="http://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/InstrumentsUserGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40004652" target="_blank">some great overviews</a>. Check them out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/10/24/ios-diary-5-tips-for-leak-free-apps/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>iOS Diary: Understanding the Application Lifecycle</title>
		<link>http://www.markbetz.net/2010/10/03/ios-diary-understanding-the-application-lifecycle/</link>
		<comments>http://www.markbetz.net/2010/10/03/ios-diary-understanding-the-application-lifecycle/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 02:58:46 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1178</guid>
		<description><![CDATA[Pretty much since the beginning of this project I&#8217;ve been aware of a bug in the iPhone app I am finishing. About a week in I figured out how to reproduce it. If you ran the app, then hit the home button to dismiss it, then tapped the program icon to bring it back and [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/thinking_about_ios2.jpg" title="" class="thickbox" rel="singlepic547" >
	<img class="ngg-singlepic ngg-left" src="http://www.markbetz.net/wp-content/gallery/cache/547__151x151_thinking_about_ios2.jpg" alt="thinking_about_ios2" title="thinking_about_ios2" />
</a>
Pretty much since the beginning of this project I&#8217;ve been aware of a bug in the iPhone app I am finishing. About a week in I figured out how to reproduce it. If you ran the app, then hit the home button to dismiss it, then tapped the program icon to bring it back and tried to switch tabs it would crash. If running in the debugger it would pop an EXC_BAD_ACCESS exception on a reference to a UIImage associated with the UITabBarController. I assumed it was just a mistake somewhere. After all, you have to &#8211; gulp &#8211; manage memory through manual reference counting (Hello, AddRef, never thought I&#8217;d see you again. How&#8217;s your buddy Release?), so the chance that we were doing one too many releases or one too few retains was not zero. I&#8217;d finish the feature set and then hunt it down.</p>
<p>When I finally got around to the hunt-it-down part things weren&#8217;t so obvious. As far as I could tell we were doing all the right things to the resources assigned to the tab bar controller. The fact that it only happened after dismissing the application with the home button and then bringing it back had to be meaningful. In fact I had been wondering for some time just what happened when the user hit the home button on an iPhod running iOS 4.x. It was obvious from application behavior that the app wasn&#8217;t exiting and restarting. At least, not every time. I started reading up on how iOS manages the application lifecycle, and some lights began going on. Apparently the home button didn&#8217;t cause an app to exit, at least not always. If the app didn&#8217;t exit it went into a background limbo state, and in that state the operating system might do things. It might, for example, &#8220;release unused views.&#8221; Oh, really? Lots of lights popped on all at once.</p>
<p>If you were used to writing applications for iOS 3.x (and the guys who started this app were), then you had birth and death to think about, just like any program. When your app started you got a call to <em>application:didFinishLaunching</em> in the app delegate, and when the app exited you got a call to <em>applicationWillTerminate</em>. Typically you allocated your resources at startup, deallocated them in the app delegate&#8217;s <em>dealloc</em> method, and life was simple. Enter iOS 4 and &#8220;fast task switching.&#8221; This facility is a component of Apple&#8217;s answer to multi-tasking in iOS 4, the entirety of which includes actual background processing, something I&#8217;m not going into now. The piece of it that is relevant here is the switching part. Task switching is what takes place when the user taps the home button, or uses something like Springboard.</p>
<p>If your app is running in the foreground, and the user switches tasks (or a phone call arrives, or anything else happens that would force the app to give up control of the screen) what happens depends on whether the app is compliant with fast task switching. By default all apps built against the 4.0 SDK are. If you want your app to exhibit the old behavior then you have to say so by putting the <em>UIApplicationExitsOnSuspend</em> key in info.plist and setting the value to true. If you do, then the app will simply exit, and <em>applicationWillTerminate</em> gets called as it used to.</p>
<p>If you don&#8217;t add that key to info.plist, then the behavior is entirely different. Oliver Drobnik has a great flowchart of the events and accompanying explanation <a href="http://www.drobnik.com/touch/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/" target="_blank">on his Dr. Touch blog</a>. Basically it goes like this: the app starts up fresh and <em>application:didFinishLaunchingWithOptions</em> is called (the replacement for <em>application:didFinishLaunching</em>), followed by <em>applicationDidBecomeActive</em>; the app is now running in foreground and gets switched; <em>applicationWillResignActive</em> is called, followed by <em>applicationDidEnterBackground</em>. After that last call the application is suspended. Unless it is actually doing background processing as alluded to above, nothing is happening, but the image is still in memory. In this stage the OS may, as mentioned, prune the app&#8217;s memory usage by releasing invisible graphics objects, and ultimately it may also dump the app from memory if it needs to. If that happens <em>applicationWillTerminate</em> will not be called. Something to keep in mind.</p>
<p>Now what happens going the other way? If the app is suspended in ram and the user taps its icon, then it first gets a call to <em>applicationWillEnterForeground</em>, followed by  <em>applicationDidBecomeActive</em>. In order to avoid the problems we were having you need to at least tear down any invisible/unused views as the app is heading for the background, and then restore these when the app is summoned to the front again, or as needed. So, does <em>applicationWillTerminate</em> ever get called? The answer is pretty much &#8220;no.&#8221; If you&#8217;re building against the 4.0 SDK that method is essentially deprecated. Except&#8230; well comments on the Dr. Touch blog indicate that maybe it still does get called if your app is running on earlier devices such as the iPhone 3. I don&#8217; t have one of those to test on, so I&#8217;ve decided they don&#8217;t exist and my app will never run on them. Solved!</p>
<p>By the way, if you want to see which apps are currently running/suspended on your iOS 4 device double-tap the Home button. The UI will slide up as it does for the Utility app, and a side-scrollable list of app icons will be displayed. When I did this for the first time I was surprised at how many apps were still resident in memory. There is a red badge on each icon that will let you kill the app, and as with a preemptive strike from the OS the app&#8217;s <em>applicationWillTerminate</em> method is not called when a user does this. In general I would ignore this list and let the OS manage the app pool, but as a developer it&#8217;s nice to know you can force an app out of ram for a restart if you need to.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/10/03/ios-diary-understanding-the-application-lifecycle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>iOS Diary: Showing an Activity Spinner Over a UITableView</title>
		<link>http://www.markbetz.net/2010/09/30/ios-diary-showing-an-activity-spinner-over-a-uitableview/</link>
		<comments>http://www.markbetz.net/2010/09/30/ios-diary-showing-an-activity-spinner-over-a-uitableview/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 02:52:13 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1158</guid>
		<description><![CDATA[I&#8217;ve only been developing for iOS for a couple of weeks now, but it&#8217;s already obvious how ubiquitous the UITableView is in user interfaces. This makes sense. iPhone/Pad/Pod apps are often of the &#8220;list info and drill&#8221; variety, and the UITableView brings a lot of utility to the, um, table for lists, and even for [...]]]></description>
			<content:encoded><![CDATA[
<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/thinking_about_ios2.jpg" title="" class="thickbox" rel="singlepic547" >
	<img class="ngg-singlepic ngg-left" src="http://www.markbetz.net/wp-content/gallery/cache/547__151x151_thinking_about_ios2.jpg" alt="thinking_about_ios2" title="thinking_about_ios2" />
</a>

<p>I&#8217;ve only been developing for iOS for a couple of weeks now, but it&#8217;s already obvious how ubiquitous the UITableView is in user interfaces. This makes sense. iPhone/Pad/Pod apps are often of the &#8220;list info and drill&#8221; variety, and the UITableView brings a lot of utility to the, um, table for lists, and even for constructing static dialogs. UITableViews automatically scroll if your content is too long for the vertical screen space, and they give you a lot of control over how individual cells and rows are styled. In the app I recently worked on we used a UITableView to list some stuff that was fetched as XML from a REST webservice. The webservice was taking about 4-5 seconds to retrieve the data over a wifi connection, and I knew it would likely be slower over 3G data connections. To let the user know what was going on I wanted to display an animated activity spinner while the transaction was enroute. If you&#8217;ve used the YouTube app for iOS then you&#8217;ve seen one of these in action.</p>

<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/ipod_youtube_spinner.jpg" title="" class="thickbox" rel="singlepic545" >
	<img class="ngg-singlepic ngg-center" src="http://www.markbetz.net/wp-content/gallery/cache/545__213x320_ipod_youtube_spinner.jpg" alt="ipod_youtube_spinner" title="ipod_youtube_spinner" />
</a>

<p>The spinner is displayed over the contents of the table view, without obstructing the tab bar control. You can freely switch to another tab while the spinner is displayed over the current tab. It&#8217;s a nice, clean way to show that one tab is busy, while allowing the other tabs in the application to remain available. When I tried to replicate this behavior in our app, however, I quickly ran into some quirks. UITableView might be a useful control, but it isn&#8217;t all that lenient about how its views are managed. More on that below. First, let&#8217;s make the spinner itself.</p>
<p>Fortunately the iOS UIKit contains a view called UIActivityIndicatorView that makes this a pretty easy task. Basically the indicator view provides the little animated spinner. You set up its properties and provide a container. Here&#8217;s what the declaration of a reusable spinner overlay might look like. The syntax highlighter doesn&#8217;t deal with Objective-C, so I am just using the C filter. Apologies if it doesn&#8217;t look right.</p>
<pre class="brush: cpp; title: ; notranslate">
// MyActivityOverlayViewController.h
#import &lt;UIKit/UIKit.h&gt;

@interface MyActivityOverlayController : UIViewController {
    UILabel *activityLabel;
    UIActivityIndicatorView *activityIndicator;
    UIView *container;
    CGRect frame;
}
-(id)initWithFrame:(CGRect) theFrame;
</pre>
<p>As you can see, not much to it. We have an interface derived from UIViewController, with ivars to hold pointers to a label, the spinner, and a container to hold them both. There is also an init method that takes a frame. I&#8217;ll talk more about this below, but essentially I found it useful to establish the size I wanted the view to be at initialization. That gets stored in the frame ivar.</p>
<p>So that&#8217;s the controller interface. Next let&#8217;s look at some key aspects of the implementation. First the init method:</p>
<pre class="brush: cpp; title: ; notranslate">
// MyActivityOverlayViewController.m
#import &quot;MyActivityOverlayViewController.h&quot;

-(id)initWithFrame:(CGRect)theFrame {
    if (self = [super init]) {
        frame = theFrame;
        self.view.frame = theFrame;
    }
    return self;
}
</pre>
<p>This is a pretty simple init method. First it saves the frame, because it will be used later to size and center the nested controls, and then it sets the size of the default view created by the UIViewController. Next we need to create the controls and build our simple view hierarchy. The overridden loadView method is where that gets done:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)loadView {
    [super loadView];
    container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
    activityLabel = [[UILabel alloc] init];
    activityLabel.text = NSLocalizedString(@&quot;Loading&quot;, @&quot;string1&quot;);
    activityLabel.textColor = [UIColor lightGrayColor];
    activityLabel.font = [UIFont boldSystemFontOfSize:17];
    [container addSubview:activityLabel];
    activityLabel.frame = CGRectMake(0, 3, 70, 25);

    activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [container addSubview:activityIndicator];
    activityIndicator.frame = CGRectMake(80, 0, 30, 30);

    [self.view addSubview:container];
    container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
    self.view.backgroundColor = [UIColor whiteColor];
}
</pre>
<p>This method does a bit more work. After calling the superclass loadView it creates a container to hold the label and activity spinner. Having them inside a container makes it easy to center the group in the owning view. It then creates the label, sets a few style properties, and adds it to the container&#8217;s view as a subview. You can set these properties any way you want. I was shooting for essentially the same look as the YouTube app. The last thing that happens to the label is that its frame is set. The size of the rectangle used was figured out based on the font size and relative positioning I wanted, but what&#8217;s important is that the size was set after the label was added to its owning view (i.e. the container). I&#8217;m not sure why this was important, but it was. Hey, I&#8217;ve only been at this a couple of weeks.</p>
<p>The next thing that happens is that the activity indicator itself is created. You&#8217;ll note that I&#8217;m not autoreleasing any of these objects, so I have to make sure to release them in the dealloc override. I know that UITableView retains its added views, and if that is also true of UIView I could autorelease the controls here and let the view manage them, but as I wasn&#8217;t sure of the behavior I opted to play it safe. After the indicator is created it is added to the container view and its frame is also set. Lastly the container itself is added to the UIViewController&#8217;s view, it&#8217;s center is set to the center of the frame we saved in the init method, and its background color is set to white.</p>
<p>Just a few additional things to finish off the implementation. First we need to start the indicator spinning. The indicator view provides methods called startAnimating and stopAnimating for just this purpose, and you could provide pass-through methods on your overlay controller. That would be the way to go if, for example, you wanted to display the overlay and then start and stop the animation and alter the label as different actions occur. In my case I&#8217;m going to have it start spinning whenever its displayed, and stop when it goes away. For that purpose you can override viewWillAppear, and viewWillDisappear:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)viewWillAppear:(BOOL) animated {
    [super viewWillAppear:animated];
    [activityIndicator startAnimating];
}

-(void)viewWillDisappear:(BOOL) animated {
    [super viewWillDisappear:animated];
    [activityIndicator stopAnimating];
}
</pre>
<p>The only other thing we need to do is clean up after ourselves:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)dealloc {
    if (container != nil) [container release];
    if (activityLabel != nil) [activityLabel release];
    if (activityIndicator != nil) [activityIndicator release];
    [super dealloc]
}
</pre>
<p>And that does it for a simple implementation of a UIView that can be initialized with a frame size, and that will create a centered combination of a light gray activity spinner and light gray label on a white background. Now all we have to do is display it somewhere. That, as it turns out, is the tricky bit.</p>
<p>To get something on the screen we have a couple of choices. We could tell the tab bar controller to present it as a modal, or to push it as a page. Neither is a very good choice in this instance. Pushed controllers are not modal; they come with a back button by default. Modal controllers take up the whole screen and prevent access to the tab bar. So that&#8217;s not what we&#8217;re after. The other alternative is to play with views. To do this we would create an instance of the ActivityOverlayViewController, and then pass its view to the addSubView method of our UITableView&#8217;s view.</p>
<p>None of my attempts at doing this worked. I tried different combinations of methods to insert the view and then bring it to the top, but whatever I did things got screwed up one way or another. Toward the end I actually got it to display, but the table view drew the cell border lines over it, and that I was not able to work around. Instead, what I had to do was insert the activity spinner view as a subview in the view that owned the table view. In other words, it had to be a sibling view of the table view, not a child, and it had to be on top. Here&#8217;s what I came up with:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)showActivityView {
    if (overlayController == nil) {
        overlayController = [[ActivityOverlayViewController alloc] initWithFrame:self.view.superview.bounds];
    }
    [self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
</pre>
<p>So the first thing to note here is that my activity controller is initialized with a rectangle representing the bounds, or inside dimension, of my table view&#8217;s superview. The second thing is that it is explicitly added to that view using the method that let&#8217;s you specify a view over which it should be placed in the view stack. In this case I want it inserted above the table view.</p>
<p>And that pretty much does it. Add that method, and an ivar to hold the pointer to the ActivityOverlayViewController, to the controller for your table view and you&#8217;re all set. To get rid of it when your background action is done, call:</p>
<pre class="brush: cpp; title: ; notranslate">
-(void)hideActivityView {
    [overlayController.view removeFromSuperView];
}
</pre>
<p>And of course remember to clean up after yourself in your dealloc method. Here&#8217;s what the result looks like&#8230;</p>

<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/ipod_ipager_spinner.jpg" title="" class="thickbox" rel="singlepic546" >
	<img class="ngg-singlepic ngg-center" src="http://www.markbetz.net/wp-content/gallery/cache/546__213x320_ipod_ipager_spinner.jpg" alt="ipod_ipager_spinner" title="ipod_ipager_spinner" />
</a>

<p>The final caveat is that as I mentioned above I am quite new to all this, so if somebody knows a better way to get this done then I hope to hear of it. Meanwhile this works and achieves the desired behavior.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/09/30/ios-diary-showing-an-activity-spinner-over-a-uitableview/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>iOS Diary: When is a Property Access Not a Property Access?</title>
		<link>http://www.markbetz.net/2010/09/19/ios-diary-when-is-a-property-access-not-a-property-access/</link>
		<comments>http://www.markbetz.net/2010/09/19/ios-diary-when-is-a-property-access-not-a-property-access/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 00:29:07 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1149</guid>
		<description><![CDATA[Today I ran into a memory error in the iOS application I am working on. The event had special significance for me because I think Clinton was president the last time I saw an actual access violation. C# .NET programmers enjoy the benefits of a managed execution environment, and we don&#8217;t see those things much [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://www.markbetz.net/wp-content/gallery/miscellaneous-article-graphics/thinking_about_ios2.jpg" title="" class="thickbox" rel="singlepic547" >
	<img class="ngg-singlepic ngg-left" src="http://www.markbetz.net/wp-content/gallery/cache/547__151x151_thinking_about_ios2.jpg" alt="thinking_about_ios2" title="thinking_about_ios2" />
</a>
 Today I ran into a memory error in the iOS application I am working on. The event had special significance for me because I think Clinton was president the last time I saw an actual access violation. C# .NET programmers enjoy the benefits of a managed execution environment, and we don&#8217;t see those things much any more. I remembered them from years of C and C++ programming, and I knew in general what to look for, but figuring out specifically what patterns represented risks in Objective-C required reading up on how memory management is handled for Cocoa apps running on iOS.</p>
<p>The answer is that it ain&#8217;t much handled at all. The scheme relies on manual reference counting using messages like retain, release, and autorelease, and there are a number of rules for when you should send these messages to a given object. One blog post I read called this a &#8220;convention-based&#8221; regime, which is a good term for it. The important thing when adhering to a convention is to understand what the rules are. Fortunately the rules for Objective-C aren&#8217;t numerous or difficult to understand. In a nutshell: if you own an object you must release it. The corollary might be: if you release an object it better be one you created, or one you have taken ownership of by sending it a retain message. The whole thing rests on knowing whether or not you own an object. One of the places where this gets tricky, as old C++ hands will have no difficulty believing, is in property sets and gets.</p>
<p>Fortunately the rules here aren&#8217;t all that obtuse either, and they boil down to: when you set a property release the current value, and retain the new value. There are some variations, but in general that&#8217;s what you&#8217;re going to want to do. Code that gets the value of a property should adhere to another rule: when you receive an object from a method not prefixed with alloc, init, or copy, or when you are passed an object as an argument to a method call, you don&#8217;t own it. You don&#8217;t release it unless you have first called retain on it. If everybody plays by those rules then everything works fine, but of course that&#8217;s always been the rub with primitive languages: voluntary compliance.</p>
<p>In any case, our code did appear to play by those rules, and yet it was still crashing. The scenario was a simple one&#8230;</p>
<pre class="brush: cpp; title: ; notranslate">
@interface SomeClass
    int someProperty;
@end
@property (retain, nonatomic) int someProperty;
</pre>
<p>The @property syntax tells the compiler to generate accessor methods named &#8216;someProperty&#8217; and &#8216;setSomeProperty&#8217; that adhere to the rules for setting and returning properties. The &#8216;retain&#8217; and &#8216;nonatomic&#8217; attributes are instructions to the compiler on how to generate those accessors, in this case adding code to release/retain in the setter, and not adding code to guarantee transactional atomicity. Based on what I could see we were adhering to best practices in using the @property syntax to implement our properties. And yet&#8230; it was still crashing.</p>
<p>The line that was faulting looked like this&#8230;</p>
<pre class="brush: cpp; title: ; notranslate">
self.anotherProperty = someProperty;
</pre>
<p>Veteran Objective-C programmers will already see a problem here. The line above was faulting trying to read someProperty. The value of someProperty had been set earlier in a line that looked like this&#8230;</p>
<pre class="brush: cpp; title: ; notranslate">
someProperty = aStringWeWerePassed;
</pre>
<p>Veteran Objective-C programmers may actually be laughing audibly at this stage of the discussion. The problem with these two lines of code is obvious to them, but it&#8217;s the kind of thing a C# programmer would blow right by without a second thought. Naturally, if you define a property and then assign to it, the setter method is going to be invoked. Right?</p>
<p>Uh, no. I&#8217;ve been learning as I proceed deeper into this thing that the best way to grok what is going on in Objective-C is to let the old C ethos flood back into your soul. If you never had a C ethos, because you never worked in C, may your deity of choice aid you. In &#8216;Old C&#8217; the compiler knows diddly squat about properties, and it doesn&#8217;t know when to turn a simple and obvious assignment into a call to a method. It doesn&#8217;t know unless you tell it, and the way to tell it is like this&#8230;</p>
<pre class="brush: cpp; title: ; notranslate">
self.someProperty = aStringWeWerePassed;
// or
[self setsomeProperty:aStringWeWerePassed];
</pre>
<p>Either of these will work, but what we were doing was a simple assignment of one pointer value to another, without going through the setter method, and without calling retain or release or any of that stuff. Specifically, the reason the program was crashing is that when you are passed an object in a method (in a callback from NSXmlParser in this case) the object is guaranteed to be around until the method that passed it to you returns. If you want to keep it longer than that you call retain on it. That&#8217;s what happens in the property setter, except that as you know now we weren&#8217;t going through the property setter when we set the value. By the time we read that value later the memory had been deallocated.</p>
<p>Objective-C, as I have grown fond of saying, actually <em>is</em> your father&#8217;s programming language.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/09/19/ios-diary-when-is-a-property-access-not-a-property-access/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>More on Remote Connections to the VS Web Server</title>
		<link>http://www.markbetz.net/2010/09/19/more-on-remote-connections-to-the-vs-web-server/</link>
		<comments>http://www.markbetz.net/2010/09/19/more-on-remote-connections-to-the-vs-web-server/#comments</comments>
		<pubDate>Sun, 19 Sep 2010 19:44:32 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1146</guid>
		<description><![CDATA[Well, I may have been a little premature in my post below on using port forwarding to connect a remote client to the Visual Studio development web server. When I tested the approach my app was able to connect and begin a request, but there was a database problem that was masking the result, and [...]]]></description>
			<content:encoded><![CDATA[<p>Well, I may have been a little premature in my post below on using port forwarding to connect a remote client to the Visual Studio development web server. When I tested the approach my app was able to connect and begin a request, but there was a database problem that was masking the result, and I assumed that when it was fixed the request would round-trip successfully. Instead I found that the request wasn&#8217;t completing because the connection was being reset. I still think the technique will work, but since I am not sure why it didn&#8217;t in this case I thought I should clarify the post. Here&#8217;s what I saw:</p>
<p>I set up the services to run under the development server on localhost:35000. I then started Portforward.exe and set up a redirect from 192.168.0.100:8888 (the dev machine&#8217;s local address) to localhost:35000. The remote client is an iOS app running on an iPod Touch connected via wifi with the address 192.168.0.111. The request was received successfully, the service processed the request successfuly, the result was serialized successfully, but once I let the program run out of the service method the client would report a connection reset. This was tested from the iPod, as well as from a simple console client on another windows box, with the same result.</p>
<p>I fired up Wireshark and monitored the exchange. The inbound request was sent in two packets. The first contained the POST header, and the second contained the request body. After the service finished processing the response header packet was written (including 200 OK and the correct content length), and then RST was sent and the connection was dropped. So, given this scenario I am sort of suspicious that the problem lies with Portforward.exe, but I don&#8217;t have time to find a different forwarder, or write one, and test it again. Until I do I can&#8217;t really say that the technique will work. In the end I had to go ahead and install IIS to enable the full debugging scenario I needed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/09/19/more-on-remote-connections-to-the-vs-web-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remote Connections to Visual Studio&#8217;s Web Server</title>
		<link>http://www.markbetz.net/2010/09/15/remote-connections-to-visual-studios-web-server/</link>
		<comments>http://www.markbetz.net/2010/09/15/remote-connections-to-visual-studios-web-server/#comments</comments>
		<pubDate>Thu, 16 Sep 2010 00:44:34 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.markbetz.net/?p=1141</guid>
		<description><![CDATA[The integrated development web server in Visual Studio is a handy tool. Since its introduction developers of ASP.NET web applications and web services have been able to build and test their code locally, without having to take the post-build step of publishing to an IIS server first. A nice tool, but a slightly crippled one. Presumably because Microsoft [...]]]></description>
			<content:encoded><![CDATA[<p>The integrated development web server in Visual Studio is a handy tool. Since its introduction developers of ASP.NET web applications and web services have been able to build and test their code locally, without having to take the post-build step of publishing to an IIS server first. A nice tool, but a slightly crippled one. Presumably because Microsoft did not want people to use the full-featured server to deploy production applications it only accepts connections from localhost. In my current work on an iOS app I wanted to issue http requests from an iPod Touch over a wifi network, and send them to a REST web service running under Visual Studio 2010 on my development machine. Ordinarily you can&#8217; t do this. You&#8217;d have to install the service code in a local instance of IIS and set VS up to step through it there.</p>
<p>If you Google around on this problem you&#8217;ll find a number of solutions. The actual code inside the server that rejects remote connections is just a couple of lines and not at all complicated. For this reason some people have suggested using ildasm to disassemble the web server assembly and comment out the relevant test. But there is a much easier and less intrusive way to get around this problem, and it just takes a couple of minutes to set up.</p>
<p>First, find and download a port forwarding utility for Windows. I use Portforward by Trent Waddington, because it is small, requires no installation, and is easy to use. His download link is to an exe file so I won&#8217;t post it here, but you can find it midway down <a href="http://www.quantumg.net/portforward.php" target="_blank">this page</a>. What you&#8217;re going to do with the port forwarding utility is make Visual Studio&#8217;s web server think your connection is coming from localhost, when in fact it is coming from a remote device.</p>
<p>Once you have the port forwarding utility, open up your VS application, and get into the project properties dialog. Click the &#8216;web&#8217; tab and look for the &#8216;Servers&#8217; section of the property page. The radio button next to &#8216;Use Visual Studio development server&#8217; should be checked. Below it check the radio button next to &#8216;specific port&#8217;, and then type a port number into the edit box on the right. I usually use 35000. Save the project properties. Build and run. Your web application is now running on the dev server and listening for http connections on whatever port you chose.</p>
<p>Now start the port forwarding utility and set up a forwarding rule. You do this in various ways in different tools, but in Portforward you click &#8220;Redirections&#8221; and then &#8220;Add&#8221; and it pops a little dialog. Let&#8217;s say that the machine you&#8217;re running the web app on has an IP of 192.168.0.100, and your client is going to try to connect to port 8080. Set up a rule that forwards 192.168.0.100:8080 to localhost:35000 and you&#8217;re good to go. Now when your client connects the connection will be redirected to the development web server on localhost, which will make it happy, and make you happy at the same time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.markbetz.net/2010/09/15/remote-connections-to-visual-studios-web-server/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

