<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by Squarespace Site Server v5.11.81 (http://www.squarespace.com/) on Fri, 01 Jun 2012 19:36:51 GMT--><feed xmlns="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/"><title>Main</title><subtitle>Main</subtitle><id>http://markstruzinski.com/main/</id><link rel="alternate" type="application/xhtml+xml" href="http://markstruzinski.com/main/"/><link rel="self" type="application/atom+xml" href="http://markstruzinski.com/main/atom.xml"/><updated>2012-05-02T20:22:42Z</updated><generator uri="http://www.squarespace.com/" version="Squarespace Site Server v5.11.81 (http://www.squarespace.com/)">Squarespace</generator><entry><title>Quick Wipe of iOS Simulator Using Alfred</title><category term="Alfred"/><category term="Utilities"/><category term="XCode"/><id>http://markstruzinski.com/main/2012/5/2/quick-wipe-of-ios-simulator-using-alfred.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2012/5/2/quick-wipe-of-ios-simulator-using-alfred.html"/><author><name>Mark.Struzinski</name></author><published>2012-05-02T19:37:16Z</published><updated>2012-05-02T19:37:16Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>When I am rapidly prototyping new features, I frequently need to blow out the entire app structure from the simulator and start fresh.</p>
<p>To do this manually, I would follow the following steps.</p>
<h2 id="fromsimulatorwhensimulatorisopen:">From Simulator (when simulator is open)*:</h2>
<ol>
<li>Go to Menu Bar</li>
<li>Click iOS Simulator</li>
<li>Click Reset Content and Settings</li>
</ol>
<h3 id="benefitsofthisapproach:">Benefits of this approach:</h3>
<ul>
<li>Easy to do/remember</li>
<li>Blows out all settings and apps</li>
</ul>
<h3 id="drawbackstothisapproach">Drawbacks to this approach</h3>
<ul>
<li>Destroys ALL content, including any general settings     
<ul>
<li>I frequently need to test something more complex, like uploading images. I will save images to the simulator by going to Safari on the simulator and saving images form the web for use in the simulator&rsquo;s photo library. Using the Reset Content option destroys all of this data and it has to be recreated.</li>
</ul>
<p>&nbsp;</p>
</li>
<li>Simulator must already be running to reset settings</li>
</ul>
<p>&nbsp;</p>
<h2 id="fromfinder">From Finder</h2>
<ol>
<li>Go to path: ~/[user]/Library/Application\ Support/iPhone\ Simulator/[SDK Version]/Applications</li>
<li>Delete all folders in the Applications folder</li>
</ol>
<h3 id="benefitsofthisapproach">Benefits of this approach</h3>
<ul>
<li>Deletes apps from simulator without wiping settings</li>
</ul>
<h3 id="drawbackstothisapproach">Drawbacks to this approach</h3>
<ul>
<li>Very manual, even when you have a sidebar shortcut set up in the Finder</li>
</ul>
<h2 id="mysolution:alfredsimulatorwipe">My solution: Alfred Simulator Wipe</h2>
<p>I love the application <a title="Alfred App" href="http://www.alfredapp.com/">Alfred</a>. Alfred is an extremely useful app that started its life as an application launcher, and has evolved into a swiss army knife that is ultimately customizable and expandable. When I get on any Mac and hit ⌘-space and see Spotlight instead of Alfred, I know my productivity will be less than normal. One of the best features of Alfred is the ability to create custom shell/Applescript extensions and run them from the app with a keyword (The devs just added the ability to pipe input into these scripts with v1.2, but I haven&rsquo;t had a chance to play with it yet). This is the technique I used to automate the majority of this simulator wipe process (You have to have purchased the PowerPack to take advantage of extensions). Here is how to create an Alfred extension to wipe your Simulator applications:</p>
<ol>
<li>
<p><a title="Alfred App" href="http://www.alfredapp.com/#download-alfred">Download Alfred</a></p>
</li>
<li>
<p>Open Alfred Preferences (with Alfred open, hit <strong>⌘,</strong>)</p>
</li>
<li>
<p>Click the &lsquo;+&rsquo; button at the bottom left of the window:</p>
<p><span class="full-image-inline ssNonEditable"><span><img style="width: 500px;" src="http://markstruzinski.com/storage/post-images/AlfredPreferences.png?__SQUARESPACE_CACHEVERSION=1335989483295" alt="" /></span></span></p>
</li>
<li>
<p>Select AppleScript</p>
</li>
<li>
<p>Enter an Extension Name. Other details are optional</p>
</li>
<li>
<p>To make it look nice in Alfred, you can drag in an icon that will be displayed in the app when the keyword is invoked</p>
</li>
<li>
<p>Enter a title and description</p>
</li>
<li>
<p>Pick a keyword that Alfred will use to launch the script</p>
</li>
<li>
<p>Check the &lsquo;background&rsquo; box (This allows the script to run and not block Alfred until it completes)</p>
</li>
<li>
<p>Use the following code in the AppleScript field:</p>
<pre class="brush: applescript; class-name: applescript; gutter: false;">
tell application &ldquo;Finder&rdquo;
delete (every item of folder &ldquo;[Drive]:Users:[user]:Library:Application Support:iPhone Simulator:5.1:Applications&rdquo;)
end tell
</pre>
<p>&nbsp;</p>
</li>
<li>
<p>The iOS simulator uses a separate directory for each installed SDK. For each iOS SDK on your system (I have 3), add a new line to delete that Simulator&rsquo;s installed apps. You would simply copy the delete line above and change [5.1] to a different folder name.</p>
</li>
<li>
<p>Click the Save button when you&rsquo;re done</p>
</li>
<li>
<p>Invoke Alfred, then type in the keyword you set up to run the extension</p>
</li>
<li>
<p>You should wind up with something like you see below</p>
</li>
</ol>
<p>&nbsp;</p>
<p><span class="full-image-block ssNonEditable"><span><img style="width: 500px;" src="http://markstruzinski.com/storage/post-images/Alfred.png?__SQUARESPACE_CACHEVERSION=1335989585400" alt="" /></span></span> Alfred Screenshot</p>
<p>&nbsp;</p>
<p>This will easily wipe out your simulator apps without destroying any data in the simulator itself. It&rsquo;s also a lot easier than going through the Finder every time. I&rsquo;m linking to an export of the extension below. Please let me know in the comments if you are doing anything similar or you can think of any improvements!</p>
<p><a title="Wipe Sim Apps.alfredextension" href="http://cl.ly/0w300M1W2B253P412n08">Alfred Simulator Wipe Extension</a></p>]]></content></entry><entry><title>Persisting Data Using the Plist Format: Part 2/2</title><category term="Cocoa"/><category term="PList"/><category term="Persistence"/><category term="iOS"/><id>http://markstruzinski.com/main/2012/2/23/persisting-data-using-the-plist-format-part-22.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2012/2/23/persisting-data-using-the-plist-format-part-22.html"/><author><name>Mark.Struzinski</name></author><published>2012-02-23T12:16:12Z</published><updated>2012-02-23T12:16:12Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>This is a follow up to my <a href="http://markstruzinski.com/main/2012/2/2/persisting-simple-data-using-the-plist-format.html">previous post</a> on persisting PList data to disk as a form of transient storage for data. This second part will just show an easy way to pull that data from disk and get it into memory in an easily usable format. </p>

<p>All of our Plists are stored as dictionaries. The keys for the dictionaries are stored as constants in a code file (<code>Constants.h/.m</code>). This allows for compiler time checking and keeps us from having to litter our code with magic strings when trying to access the values.</p>

<p>Here is a sample workflow to get this method up and running:</p>

<h2 id="theplistdata">The PList Data</h2>

<p>Assuming we have a plist that contains the following data:</p>

<pre class="brush: xml">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;
&lt;plist version=&quot;1.0&quot;&gt;
&lt;dict&gt;
    &lt;key&gt;firstName&lt;/key&gt;
    &lt;string&gt;Mark&lt;/string&gt;
&lt;/dict&gt;
&lt;/plist&gt;
</pre>

<h2 id="createaconstantsfileandalwaysuseit">Create a Constants File, and Always Use It</h2>

<p>Create a Constants file, and add all keys to it as <code>const NSString</code>. Be strict and only reference these keys when attempting to access data from your NSDictionaries. Don’t shortcut and put the strings directly into your code. Here is an example of how I have this set up:</p>

<h4 id="constants.h">Constants.h</h4>

<pre class="brush: objc">#import &lt;Foundation/Foundation.h&gt;

@interface Constants : NSObject

extern NSString * const DICT_KEY_FIRST_NAME;

@end
</pre>

<h4 id="constants.m">Constants.m</h4>

<pre class="brush: objc">#import &quot;Constants.h&quot;

@implementation Constants

NSString * const DICT_KEY_FIRST_NAME   = @&quot;firstName&quot;;

@end
</pre>

<h2 id="addyourconstantsfiletoyourpre-compiledheadersfilesoitisavailableeverywhere">Add your Constants file to your pre-compiled headers file so it is available everywhere</h2>

<p>Adding files to your pre-compiled headers makes them available everywhere in your project without having to import each specific class header in the file where you’re trying to use it. Use this convenience judiciously, and only for classes that you truly think you’ll need everywhere. I always include my Constants file in the pre-compiled header to ensure I can access it without having to import it everywhere.</p>

<p>You can find your pre-compiled header file in the <strong>Supporting Files</strong> group in your project navigator in XCode (if you haven’t moved it). It is typically named <code>{projectname}-Prefix.pch</code>, where {projectname} is the name of your project. At the bottom of this file, you can add #import statements for the header fields you are interested in. Your file should look something like this:</p>

<pre class="brush: objc">//
// Prefix header for all source files of the 'FeverMonitor' target in the 'FeverMonitor' project
//

#import &lt;Availability.h&gt;

#ifndef __IPHONE_3_0
#warning &quot;This project uses features only available in iOS SDK 3.0 and later.&quot;
#endif

#ifdef __OBJC__
    #import &lt;UIKit/UIKit.h&gt;
    #import &lt;Foundation/Foundation.h&gt;
    #import &lt;CoreData/CoreData.h&gt;
    #import &quot;Constants.h&quot;
#endif
</pre>

<p>The import statement you’re interested in the last one. Make sure you add it inside the <code>#ifdef__OBJC__</code> block.</p>

<p>This adds an #import statement for each file at compile time which includes these files throughout your entire project. It will also update XCode’s autocomplete indexing so that you are able to use autocomplete for the code on the imported files. </p>

<h2 id="pullyourfilefromdiskandusetheconstantsdefined">Pull your file from disk, and use the constants defined</h2>

<p>Here is an example of how we could wrap this all up and pull some data from a plist file already on disk:</p>

<pre class="brush: objc">    NSString *filepath = [self convenienceMethodToGetFilePathForPlist];
    NSDictionary *resultsDict = [NSDictionary dictionaryWithContentsOfFile:filepath];
    NSString *firstName = [resultsDict objectForKey:DICT_KEY_FIRST_NAME];

    NSLog(@&quot;First Name: %@&quot;,firstName);
</pre>

<p>Note above that you will need a way to get the plist file path before being able to access it. Also note that I prefix the string constant with <code>DICT_KEY</code>. I do this so that as my constants file grows, I can easily locate the value I’m looking for by typing the prefix I’m looking for. </p>

<p>Well, that wraps up this segment. As a caveat here, I’d like to mention that this data storage methodology, in my opinion, would not scale to larger data sets. You should definitely consider using <a href="https://developer.apple.com/library/mac/#documentation/cocoa/conceptual/coredata/cdprogrammingguide.html">Core Data</a> for the majority of your data storage scenarios. We decided to use the PList format in this case because the data was transient, and was going to be wiped out on each subsequent change to it.</p>]]></content></entry><entry><title>Persisting Simple Data Using the Plist Format</title><category term="Cocoa"/><category term="PList"/><category term="Persistence"/><category term="iOS"/><id>http://markstruzinski.com/main/2012/2/2/persisting-simple-data-using-the-plist-format.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2012/2/2/persisting-simple-data-using-the-plist-format.html"/><author><name>Mark.Struzinski</name></author><published>2012-02-03T04:16:44Z</published><updated>2012-02-03T04:16:44Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>Recently, we had the need to save some simple transient data to disk. For data of any significant size, we would have looked at Core Data for our persistence. In this case, we decided to use the PList format to save data to disk and pull it back off. We went through several ideas to store this data. </p>

<p>Some of the ideas we considered for persistence included:</p>

<ul>
<li>Core Data</li>
<li>JSON saved in a flat file format</li>
<li>PList saved directly to disk from a Cocoa object such as an NSArray or NSDictionary</li>
</ul>

<p>Because of our specific set of requirements and our hardware stack, we opted to go with the PList format. Our main driver for this decision was the amount of control we have over the response format from the server. Since we control our servers and their output, we are able to specify PList as a return type. We use the excellent <a href="https://github.com/AFNetworking/AFNetworking">AFNetworking</a> library to perform our networking tasks. </p>

<p>The AFNetworking library has a request named <a href="http://engineering.gowalla.com/AFNetworking/Classes/AFPropertyListRequestOperation.html">AFPropertyListRequestOperation</a>.* This operation will take an NSURLRequest and return an <code>id</code> that can be cast to a native Cocoa object, such as an NSDictionary or NSArray. Because we know the object’s return structure, we directly cast our object and move on to processing it. From there, it is just a matter of using the <code>writeToFile:Atomically</code> method to persist to disk. </p>

<p>Here is an example workflow:</p>

<pre class="brush: objc">NSString *urlString = @&quot;http://api.responder?format=plist&quot;;
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL urlWithString:urlString]];
    AFPropertyListRequestOperation *operation = 
    [AFPropertyListRequestOperation propertyListRequestOperationWithRequest:urlString success:^(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList) {
            // Cache the response
        NSDictionary *responseDict = (NSDictionary *)propertyList;
        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachesPath = [pathArray lastObject];
        NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:cachesPath,@&quot;responseDict.plist&quot;,nil]];
        BOOL success = [responseDict writeToFile:filePath atomically:YES];
        if(!success){
            // Handle error
        }        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList) {
        NSLog(@&quot;API Call failure: %@&quot;,[error localizedDescription]);
    }];
</pre>

<p>One caveat here is to be careful that your dictionary is properly formatted when being returned from the server, and when attempting to save to disk. Initially, we had some bugs when nulls were encountered as a response from the server for specific values. The server parsing logic would simply not generate a value for the key if the value was null. In PList format, this is unacceptable syntax. If you tried to save this to disk, the call would fail and return NO from the <code>writeToFile: method</code>.</p>

<p>For my next post, I’ll do a quick follow up on how to pull the data back off of disk and get it into a usable format in memory.</p>

<p>*<em>Please note that the headers returned from the server must specify <code>application/x-plist</code> data format. The AFPropertyListRequestOperation will check for this in the header and fail the request if it is not present.</em></p>]]></content></entry><entry><title>Goodbye, Steve</title><category term="Apple"/><category term="Apple"/><id>http://markstruzinski.com/main/2011/10/6/goodbye-steve.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2011/10/6/goodbye-steve.html"/><author><name>Mark.Struzinski</name></author><published>2011-10-06T05:31:23Z</published><updated>2011-10-06T05:31:23Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>I didn’t become an Apple user until a few years ago. I came to the platform out of curiosity. I bought myself a Macbook to start teaching myself how to code iOS apps. I quickly found myself amazed at the ingenuity and simplicity of the entire platform. It was the way everything tied together, and always seemed to work in the way you expected. The more I lived in the Apple world, the more impressed I became. In 3 years, I have gone from using Apple’s products as a hobby to a full time developer on their platform. For the first time in my life, I have questioned that someone actually pays me to work on this stuff. I guess if you ask yourself that question, you are doing the right thing with your life.</p>

<p>I was surprised and saddened to hear of Steve Jobs’ passing tonight. He truly made a difference in our world with sheer will and by questioning everything. His stamp is all over these products we all use every day for entertainment and for work. His drive and determination produced these incredible products and services which set the standard for excellence in technology. </p>

<p>A quote out of the recent statement by President Obama on Steve Jobs’ passing struck me as particularly apt:</p>

<blockquote>
<p><em>“The world has lost a visionary. And there may be no greater tribute to Steve’s success than the fact that much of the world learned of his passing on a device he invented.”</em></p>
</blockquote>

<p>I was glad to hear he passed peacefully and with his family. </p>

<p>Rest in peace, Steve. Our world is a little less without you in it.</p>]]></content></entry><entry><title>Quick Xcode 4 Tip: Deleting Derived Data to Rescue Code Completion</title><category term="Productivity"/><category term="XCode"/><category term="XCode"/><id>http://markstruzinski.com/main/2011/9/29/quick-xcode-4-tip-deleting-derived-data-to-rescue-code-compl.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2011/9/29/quick-xcode-4-tip-deleting-derived-data-to-rescue-code-compl.html"/><author><name>Mark.Struzinski</name></author><published>2011-09-30T03:52:00Z</published><updated>2011-09-30T03:52:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p><h2>Quick Tip:</h2></p>

<p>I had an issue on a very large project in XCode. Starting 2 days ago, all of my syntax highlighting was completely broken. This is bad, but even worse, my code completion worked only partially. I was getting autocomplete for local variables only. When calling framework methods with a lot of parameters, I rely pretty heavily on code completion. I tried all of the usual fixes. This includes:</p>

<ol>
<li>Doing a <strong>Project Clean</strong> (⌘⇧K)</li>
<li>Doing a <strong>Clean Build Folder</strong> (⌥⌘⇧K)</li>
<li>Restarting XCode</li>
</ol>

<p>None of these solutions fixed the issue. After some digging, I came across <a href="http://stackoverflow.com/questions/5365212/xcode-4-code-loses-syntax-coloring-when-importing-project-from-xcode-3/5368489#5368489">this StackOverflow Post</a> which pointed me in the right direction. Seems like sometimes the project index, which contains metadata used to display code completion suggestions (among other things), can become corrupted. The solution is to delete it. This will force XCode to regenerate it, which rebuilds the index. </p>

<p>Here are the steps to delete your Derived Data folder.</p>

<ol>
<li><p>Go to XCode Settings (⌘,)</p></li>
<li><p>Click the Locations tab. You will see a screen like this: </p></li>
<img src="http://markstruzinski.com/resource/Locations-1.png?fileId=14407535" alt="Locations 1" title="Locations-1.png" border="0" width="600" height="422" />

<li><p>Click the small arrow next to the location of the Derived Data folder. This will open the Finder to the location of the Derived Data for any XCode projects you currently have on your Mac.</p></li>
<li><p>Find the one that starts with the name of your current project and delete it.</p></li>
<li><p>You should immediately see XCode start to re-index your project</p></li>
</ol>

<p>For me, after this process completed, I got all of my functionality back. Your mileage may vary, and please make sure you back everything up before deleting anything!</p>]]></content></entry><entry><title>BackBlaze, MDS Worker, and Spotlight</title><category term="General Tips"/><category term="Mac"/><id>http://markstruzinski.com/main/2011/8/8/backblaze-mds-worker-and-spotlight.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2011/8/8/backblaze-mds-worker-and-spotlight.html"/><author><name>Mark.Struzinski</name></author><published>2011-08-08T10:52:58Z</published><updated>2011-08-08T10:52:58Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>I recently began experiencing my system fans kicking in and running all the time. The fans began running so much that I almost didn&rsquo;t notice them any more. When I pulled the Activity Monitor up, the <strong><a href="http://osxdaily.com/2009/09/14/mdworker-what-is-mdworker/">md worker</a></strong> was using over 100% of my system resources consistently.</p>
<p>After looking up what md worker does, it appears to be a process spun off by spotlight to index your drive for quick searching. Even after a reboot, the fans would kick back in after a short idle time of maybe a minute. This process was seriously heating up the mac.</p>
<p>After doing some more research, I found this <a href="http://superuser.com/questions/46195/why-does-mds-run-wild-in-mac-os-x-10-6">excellent question and answer</a> from the SuperUser site. I ran the following command in the terminal to log what Spotlight was trying on index at the time.</p>
<pre><code>sudo fs_usage -w -f filesys mdworker</code></pre>
<p>The terminal showed the last file to be indexed was in the /Library/BackBlaze/bzdata folder. This was not Library in ~/Users, but the one at the base of the volume. It was indexing this file over and over. My initial thought was that the system was hung on the file. A google search turned up <a href="http://www.backblaze.com/help-mac.html#filevault">this result</a> on the BackBlaze support page. BackBlaze frequently writes log data to a file. All files in the BackBlaze folder should be added to the Privacy exclusions so that Spotlight will not attempt to index them. According to the support article, this exclusion should be added when BackBlaze is installed. Since the Lion version for BackBlaze was very recently released, this may be a bug in the BackBlaze installer.</p>
<p><img title="help-mac-spotlight.jpg" src="http://markstruzinski.com/resource/help-mac-spotlight.jpg?fileId=13570859" border="0" alt="Help mac spotlight" width="550" height="472" /></p>
<p>In my case, the folder had not been added.</p>
<p>After adding the BackBlaze folder to the Spotlight Privacy exclusions, the problem disappeared at once. Good job on BackBlaze for having an excellent support document.</p>
<p>&nbsp;</p>
<p><strong>UPDATE:</strong> I recently had to replace my hard drive and decided to do a fresh install rather than pulling over my <a href="http://www.bombich.com/">Carbon Copy Cloner</a> backup. I experienced the exact same problem, and had to follow the process outlined above to fix it. This issue hasn't been resolved in the BackBlaze installer as of yet.</p>]]></content></entry><entry><title>On Discovering New APIs</title><category term="Cocoa"/><category term="iOS"/><id>http://markstruzinski.com/main/2011/6/10/on-discovering-new-apis.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2011/6/10/on-discovering-new-apis.html"/><author><name>Mark.Struzinski</name></author><published>2011-06-11T03:31:00Z</published><updated>2011-06-11T03:31:00Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>In working with any programming language, I've always found that if you seem to be fighting things to get work done, you're probably doing it wrong. This is especially true in Cocoa Touch. When i was first learning the frameworks, I read a lot of blogs, books, and any other materials I could get my hands on. ALmost everyone said something to the effect of <em>"You don't get it? Read the docs again."</em></p>

<p>It took me a while to realize that Apple has excellent documentation. It's gotten a lot better in the Microsoft world, but in the C# 2.0 and 3.5 days, you would frequently go in search of a particular framework method or property, and come across a blank page that was obviously generated by some kind of tool. Or, my favorite was when you had a property that was named something like ToolsArray, and the description would contain verbiage like "The array that holds the tools".</p>

<p>Apple has excellent documentation that gives common sense user cases, detailed definitions, and, in most cases, real world usage examples. I was reading the excellent new book <a href="http://pragprog.com/titles/cdirec/ios-recipes">iOS Recipes</a> by <a href="http://www.appleoutsider.com/">Matt Drance</a> and <a href="http://twitter.com/#!/pawpoise">Paul Warren</a>, and discovered a new gem. This one is on the UserDefaults class.</p>

<p>I use the UserDefaults class in a few places in my apps, mostly to hold and maintain state, such as if the app has been launched, if the user has been registered, etc. I always found myself writing guard code like this:</p>

<pre class="brush: objc">

BOOL appWasLoaded = NO;
NSUserDefaults *standardDefaults = [NSUserDefaults standardDefaults];
if([defaults objectForKey:@"appLoadedKey"]{
    appWasLoaded = [defaults boolForKey:@"appLoadedKey"];
}

</pre>

<p>There is a way to ensure user defaults have some pre-configured settings, which will reduce some of the redundancy in testing that user settings key/value pairs exist. This is accomplished using the following method call on the user defaults:</p>

<pre class="brush: objc">

[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];

</pre>

<p>When you make this method call, the defaults variable is an NSDictionary that contains they keys and values you want to set as initial defaults. The best part about this particular method, though, is that it will only set the values in user defaults if they don't already exist. What I have been doing to set these initial defaults is to create a .plist file that includes my default values. I pass this into the code as a dictionary, then call the registerDefaults method on startup to provide the default values at runtime. Here is a quick example:</p>

<p>My PList looks like this:</p>

<pre class="brush: xml">    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
        <dict>
            <key>Test</key>
            <string>TestValue</string>
        </dict>
    </plist>
</pre>

<pre class="brush: objc">

    NSDictionary *defaultValues = 
        [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"defaultValues" 
                                                                                   ofType:@"plist"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];

</pre>

<p>After this point, calling <pre class="brush: objc">[[NSUserDefaults standardUserDefaults] stringForKey:@"Test"]</pre> will get you the string "TestValue", even if you haven't initialized it somewhere else in your code.</p>

<p>For a full rundown, make sure you check out the <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/UserDefaults/Tasks/UsingDefaults.html">official documentation</a>.</p>
]]></content></entry><entry><title>Using NSXMLParser</title><id>http://markstruzinski.com/main/2011/6/7/using-nsxmlparser.html</id><link rel="alternate" type="text/html" href="http://markstruzinski.com/main/2011/6/7/using-nsxmlparser.html"/><author><name>Mark.Struzinski</name></author><published>2011-06-08T01:54:24Z</published><updated>2011-06-08T01:54:24Z</updated><content type="html" xml:lang="en-US"><![CDATA[<p>
	This is my first stab at an iPhone project. I'm writing an app that 	consumes an RSS feed and parses it to retrieve a few bits of 	information for display on the screen. This is my first attempt at an 	implementation. Coming from a .NET background, it is quite a paradigm 	shift when switching to the heavily convention based world of Cocoa 	development. 
</p>

<p>
	If I was writing this app in .NET, I'd go out looking for the proper 	class libraries to parse the XML and begin framing out a class to 	perform all the functions I needed to populate an object to be 	persisted to the UI. 
</p>

<p>
	When researching the best way to do this, I found 2 prevalent methods 	of parsing XML in Cocoa:

	<ul>
		<li>
			<a href="http://developer.apple.com/mac/library/				documentation/Cocoa/Reference/Foundation/Classes/				NSXMLParser_Class/Reference/						Reference.html">NSXMLParser</a>
		</li>
		<li>
			<a href="http://code.google.com/p/touchcode/wiki/				TouchXML">TouchXML/libXML</a>
		</li>
	</ul>
</p>

<p>
	I decided to go with NSXMLParser because it seemed like the path of least friction to get started with. NSXMLParser is a stream based reader. It basically reads the entire XML tree character by character and fires off events via delegate calls when it encounters useful information. I found this model very easy to use. After some trial and error, I've got it working well for my current project. 
</p>

<p>
	I am parsing the xml feed for <a href="www.woot.com/salerss.aspx">Woot.com</a>. The following is an abbreviated snippet of the elements I am interested in. The actual feed has a lot more info in it, but this should give you a feel for the structure:

<p>

<div>

<pre class="brush: xml">
<channel>
    <copyright />
    <description>Woot! - One Day, One Deal</description>
    <docs>http://www.rssboard.org/rss-specification</docs>
    <generator>Oppositional.Syndication, 1.0.0.0, http://www.oppositionallydefiant.com/</generator>
    <item>
      <description>[Removed for brevity]</description>
      <link>http://www.woot.com/</link>
      <title>Dyson DC24 Blueprint Limited Edition</title>
      <woot:price xmlns:woot="http://www.woot.com/">$279.99</woot:price>
      <woot:soldout xmlns:woot="http://www.woot.com/">False</woot:soldout>
<woot:wootoff xmlns:woot="http://www.woot.com/">False</woot:wootoff>
      <woot:purchaseurl xmlns:woot="http://www.woot.com/">http://www.woot.com/WantOne.aspx?id=e94aa72d-5860-4f9b-bab2-42211de2f4cc</woot:purchaseurl>
      <woot:thumbnailimage xmlns:woot="http://www.woot.com/">http://sale.images.woot.com/Dyson_DC24_Blueprint_Limited_EditionbklThumbnail.jpg</woot:thumbnailimage>
      <woot:substandardimage xmlns:woot="http://www.woot.com/">http://sale.images.woot.com/Dyson_DC24_Blueprint_Limited_EditionxxcShoppingYahoo.jpg</woot:substandardimage>
      <woot:standardimage xmlns:woot="http://www.woot.com/">http://sale.images.woot.com/Dyson_DC24_Blueprint_Limited_Editionm32Standard.jpg</woot:standardimage>
      <woot:detailimage xmlns:woot="http://www.woot.com/">http://sale.images.woot.com/Dyson_DC24_Blueprint_Limited_Edition98lDetail.jpg</woot:detailimage>
      <woot:shipping xmlns:woot="http://www.woot.com/">$5 shipping</woot:shipping>
	</item>
</channel>	
</pre>
</div>

<h3>Defining the Model Object</h3>
<p>
	The first thing I did was create a model object which would encapsulate the element values from the rss feed that I was interested in. Here is the code for the class:
</p>

<div>
<h4>SaleItem.h</h4>
<pre class="brush: objc">
#import <Foundation/Foundation.h>


@interface SaleItem : NSObject {
	NSString *itemTitle;
	NSString *itemPrice;
	NSString *itemThumbnaillUrl;
	NSString *itemSubstandardImageUrl;
	NSString *itemStandardImageUrl;
	NSString *itemDetailImageUrl;
	NSString *itemDescription;
	NSString *itemShippingCost;
	NSString *itemSaleUrl;
	
	BOOL isWootOff;
}

@property (nonatomic, retain) NSString *itemTitle;
@property (nonatomic, retain) NSString *itemPrice;
@property (nonatomic, retain) NSString *itemThumbnaillUrl;
@property (nonatomic, retain) NSString *itemSubstandardImageUrl;
@property (nonatomic, retain) NSString *itemStandardImageUrl;
@property (nonatomic, retain) NSString *itemDetailImageUrl;
@property (nonatomic, retain) NSString *itemDescription;
@property (nonatomic, retain) NSString *itemShippingCost;
@property (nonatomic, retain) NSString *itemSaleUrl;

@property (nonatomic, assign) BOOL isWootOff; 

@end
</pre>

<h4>SaleItem.m</h4>
<pre class="brush: objc">
#import "SaleItem.h"


@implementation SaleItem

@synthesize itemTitle;
@synthesize itemPrice;
@synthesize itemThumbnaillUrl;
@synthesize itemSubstandardImageUrl;
@synthesize itemStandardImageUrl;
@synthesize itemDetailImageUrl;
@synthesize itemDescription;
@synthesize itemShippingCost;
@synthesize itemSaleUrl;
@synthesize isWootOff;


-(void) dealloc{
	[itemTitle release];
	[itemPrice release];
	[itemThumbnaillUrl release];
	[itemSubstandardImageUrl release];
	[itemStandardImageUrl release];
	[itemDetailImageUrl release];
	[itemDescription release];
	[itemShippingCost release];
	[itemSaleUrl release];	
	
	[super dealloc];
}

@end
</pre>


</div>

<div>
	<h3>Defining a Class to Reference Constants</h3>
	<p>
		Next, to make my life easier, I defined a class to define some constants. These constants define the string values I will be searching for as I parse the XML.
	</p>
	
<h4></h4>
	<div>
	<h4>Constants.h</h4>
<pre class="brush: objc">
#import <Foundation/Foundation.h>

extern NSString * const ITEM;
extern NSString * const TITLE;
extern NSString * const PRICE;
extern NSString * const THUMBNAIL_IMAGE;
extern NSString * const SUBSTANDARD_IMAGE;
extern NSString * const STANDARD_IMAGE;
extern NSString * const DETAIL_IMAGE;
extern NSString * const DESCRIPTION;
extern NSString * const IS_WOOTOFF;
extern NSString * const SHIPPING_PRICE;
extern NSString * const SALE_URL;

@interface Constants : NSObject {
	
}
</pre>


	<h4>Constants.m</h4>
<pre class="brush: objc">
#import "Constants.h"
@implementation Constants
	NSString * const ITEM				= @"item";
	NSString * const TITLE				= @"title";
	NSString * const PRICE				= @"woot:price";
	NSString * const THUMBNAIL_IMAGE	= @"woot:thumbnailimage";
	NSString * const SUBSTANDARD_IMAGE	= @"woot:substandardimage";
	NSString * const STANDARD_IMAGE		= @"woot:standardimage";
	NSString * const DETAIL_IMAGE		= @"woot:detailimage";
	NSString * const DESCRIPTION		= @"description";
	NSString * const IS_WOOTOFF			= @"woot:wootoff";
	NSString * const SHIPPING_PRICE		= @"woot:shipping";
	NSString * const SALE_URL			= @"woot:purchaseurl";
@end
</pre>
	</div>
</div>

<h3>Creating the Worker Class</h3>
<p>
	NSXMLParser works using delegate callbacks to let you hook into events that you are interested in. Most of the examples I found online used delegate methods right inside the viewcontroller to accomplish the parsing. Since I have several views which are going to take advantage of this functionality, I decided to split it out into a worker class. Let's construct this class (I named it XMLParser) piece by piece:
</p>


<h4>XMLParser.h</h4>

<pre class="brush: objc">
#import <UIKit/UIKit.h>

@class Constants; //Forward declaration of the Constants class
@class SaleItem;  //Forward declaration of the SaleItem model object class

@interface XMLParser : NSObject {
	NSMutableString *currentValue; //This will hold element values as we build them piece by piece
	BOOL itemElementInProgress;	// This will determine if we are currently parsing an element
	SaleItem *saleItem; // Instance of our model object
}

@property (nonatomic, retain) NSMutableString *currentValue;
@property (nonatomic, retain) SaleItem *saleItem;
@property BOOL itemElementInProgress;

- (BOOL) parse; // This performs the parsing of the file
- (id)initWithSaleItem:(SaleItem *)aSaleItem; // Custom initializer
- (void) trimString; // Small convenience method to remove whitespace

@end
</pre>

<h4>Building XMLParser.m</h4>

<p>Lets start with our basic shell:</p>

<div>
<pre class="brush: objc">
#import "Constants.h"
#import "SaleItem.h"
#import "XMLParser.h"

@implementation XMLParser
	// Synthesize our properties
	@synthesize currentValue;
	@synthesize itemElementInProgress;
	@synthesize saleItem;

	// Make sure objects are released
	-(void)dealloc{
		[currentValue release];
		[saleItem release];
		[super dealloc];
	}

@end
</pre>
</div>

<p>Now, let's create the initializer. Add the following code directly after the property @synthesize calls:</p>

[cc lang="objc" tab_size="2" lines="-1"]
	// Sets the saleItem property to a SaleItem object passed in 
	- (id)initWithSaleItem:(SaleItem *)aSaleItem{
		if (self = [super init]) {
			[self setSaleItem:aSaleItem];
			[self setItemElementInProgress:NO];
		}
		
		return self;
	}
[/cc]

<p>I am initializing the class this way so I can populate the SaleItem inside of XMLParser and still have access to it from the calling class (a ViewController) when I'm done parsing.
</p>

<p>
	Before we get into how to instantiate NSXMLParser and use it to parse a file, let's set up the delegate methods to get the data we need out of the file.
</p>

<p>
	I usually put delegate methods at the bottom of the file, right after a <a href="http://cocoasamurai.blogspot.com/2006/09/tip-pragma-mark-organizing-your-source.html">#pragma mark</a> definition to delineate this group of methods from the rest of the code. Hop down to the bottom of XMLParser.m, and place this code just prior to @end:
</p>

<div id="" class="">
<pre class="brush: objc">
#pragma mark NSXMLParser Delegate Calls
// This method gets called every time NSXMLParser encounters a new element
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
	 namespaceURI:(NSString *)namespaceURI 
	qualifiedName:(NSString *)qualifiedName 
	   attributes:(NSDictionary *)attributeDict{
		// If element is named "item", set bool to true so we know
		// we are inside the element in other methods. This is needed
		// because "item" contains most of the data we need
		if ([elementName isEqualToString:ITEM]) {
			[self setItemElementInProgress:YES];
		}
	}

// This method gets called for every character NSXMLParser finds.
	-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
		// If currentValue doesn't exist, initialize and allocate
		if (!currentValue) {
			currentValue = [[NSMutableString alloc] init];
		}
		
		// Append the current character value to the running string
		// that is being parsed
		[currentValue appendString:string];
	}
</pre>
</div>

<p>The final delegate method is fired when NSXMLParser reaches the end of an element. Here is the place we can be sure we have gotten the full value of the element, and can now persist that data to our model object for use. right after the foundCharacters method, add this method:</p>

<div id="didEndElement" class="">
<pre class="brush: objc">
// This method is called whenever NSXMLParser reaches the end of an element
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
									 namespaceURI:(NSString *)namespaceURI 
									qualifiedName:(NSString *)qName{
	[self trimString];  // Remove whitespace with a convenience method
	
	if ([elementName isEqualToString:ITEM]) {
		[self setItemElementInProgress:NO];  // If we are currently on the "item" element, then do not save value
	}


	// If we are processing an element inside of "item", 
	// then determine if we need to save the value	
	if (self.itemElementInProgress) {
		// Now check the element id against the ones we are 
		// interested in (using the Constants class values).
		// If we find one, set the corresponding property on the 
		// SaleItem object
		if ([elementName isEqualToString:TITLE]) {
			[[self saleItem] setItemTitle:currentValue];
		}
			 
		if ([elementName isEqualToString:PRICE]) {
			[[self saleItem] setItemPrice:currentValue];
		}
		
		if ([elementName isEqualToString:THUMBNAIL_IMAGE]) {
			[[self saleItem] setItemThumbnaillUrl:currentValue];
		}
		
		if ([elementName isEqualToString:SUBSTANDARD_IMAGE]) {
			[[self saleItem] setItemSubstandardImageUrl:currentValue];
		}
		
		if ([elementName isEqualToString:STANDARD_IMAGE]) {
			[[self saleItem] setItemStandardImageUrl:currentValue];
		}
		
		if ([elementName isEqualToString:DETAIL_IMAGE]) {
			[[self saleItem] setItemDetailImageUrl:currentValue];
		}

		if ([elementName isEqualToString:DESCRIPTION]) {
			[[self saleItem] setItemDescription:currentValue];
		}
		
		if ([elementName isEqualToString:SHIPPING_PRICE]) {
			[[self saleItem] setItemShippingCost:currentValue];
		}
		
		if ([elementName isEqualToString:SALE_URL]) {
			[[self saleItem] setItemSaleUrl:currentValue];
		}
	}
	
	[currentValue release];
	currentValue = nil;
}
</pre>
</div>

<h3>The Parse Method</h3>

<div>
	Finally, the whole process is started by the parse method:
</div>

<div>
<pre class="brush: objc">
		- (BOOL)parse{
		// Create and initialize an NSURL with the RSS feed address and use it to instantiate NSXMLParser
		NSURL *url = [[NSURL alloc] initWithString:@"http://www.woot.com/salerss.aspx"];
		NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

		// Tell NSXMLParser that this class is its delegate
		[parser setDelegate:self];
		
		// Kick off file parsing
		[parser parse];
		
		// Clean up
		[url release];
		
		[parser setDelegate:nil];
		[parser release];
		return YES;
	}
</pre>
</div>

<div>
	<h3>Final Notes</h3>
	<p>Some final thoughts on the methodology I am using:</p>
	<ul>
	<li>I want to get rid of the if statements and use Key-Value coding to set property values. I haven't gotten the chance to refactor this</li>
<li>I am very new to Cocoa, and any suggestions/comments are welcome and encouraged!</li>
	</ul>
			
</div>]]></content></entry></feed>
