<?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>Karl Kraft &#187; TheCodeBook &#8211; Snippets</title>
	<atom:link href="http://www.karlkraft.com/index.php/category/thecodebook-snippets/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.karlkraft.com</link>
	<description>Just a 2 bit programmer in a 64 bit world</description>
	<lastBuildDate>Thu, 24 Jun 2010 14:20:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>A drop-in replacement for NSLog()</title>
		<link>http://www.karlkraft.com/index.php/2009/03/23/114/</link>
		<comments>http://www.karlkraft.com/index.php/2009/03/23/114/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 16:41:58 +0000</pubDate>
		<dc:creator>Karl Kraft</dc:creator>
				<category><![CDATA[TheCodeBook - Snippets]]></category>

		<guid isPermaLink="false">http://www.karlkraft.com/?p=114</guid>
		<description><![CDATA[I recently saw this post on turning off NSLog for non-debug builds, and found it disappointing and inspirational at the same time. Scattering hundreds of #ifdefs around code is a recipe for disaster. Eventually some non debugging code will end up inside the #ifdef and the debug and release builds will function differently, making debugging [...]]]></description>
			<content:encoded><![CDATA[<p>I recently saw <a href="http://iphoneincubator.com/blog/debugging/how-to-create-conditional-log-statements-in-xcode"> this post</a> on turning off NSLog for non-debug builds, and found it disappointing and inspirational at the same time.  Scattering hundreds of #ifdefs around code is a recipe for disaster.  Eventually some non debugging code will end up inside the #ifdef and the debug and release builds will function differently, making debugging more difficult.</p>
<p>I&#8217;m not a big fan of debugging from log statements, but they can occasionally be useful.</p>
<p>What follows is details on building a full NSLog() replacement that turns off with a single #ifdef in the header file that contains the function.  You can either download the <a href="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-000.zip">m and h file</a>, or continue on to the extended entry for an explanation of how it works and ways to make it more useful for your particular needs.</p>
<p><span id="more-114"></span></p>
<p>Start with a basic Xcode Foundation Tool.  This will contain a main.m file that uses NSLog to print &#8220;Hello World!&#8221;<br />
<img src="http://www.karlkraft.com/wp-content/uploads/2009/03/xcode-001.png" alt="Xcode_001.png" border="0" width="300" height="255" /></p>
<pre>
  NSLog(@"Hello, World!");
</pre>
<p>The output will look like this:</p>
<pre>
  2009-03-23 10:57:13.619 DebugLog[11941:807] Hello, World!
</pre>
<p>Add a DebugLog.h and DebugLog.m to the file.  DebugLog.h should declare a method DebugLog() that will be the replacement for NSLog()</p>
<pre>
  void DebugLog(NSString *format,...);
</pre>
<p>And DebugLog.m should contain the implementation of that function. A particular item to note is that NSLog only adds a newline to the end of the NSLog format if one is not already there.  This function duplicates this feature of NSLog()</p>
<pre>
  void DebugLog(NSString *format,...) {
    va_list ap;
    va_start (ap, format);
    if (![format hasSuffix: @"\n"]) {
      format = [format stringByAppendingString: @"\n"];
    }
    NSString *body =  [[NSString alloc] initWithFormat: format arguments: ap];
    va_end (ap);
    fprintf(stderr,"%s",[body UTF8String]);
    [body release];
  }
</pre>
<p>You can <a href="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-001.zip" title="DebugLog_001.zip">download the project at this stage</a>.  If you play with the project at this point you will notice the output is different than NSLog().</p>
<pre>
  // With NSLog
  2009-03-23 11:01:32.936 DebugLog[12085:807] Hello, World!
  2009-03-23 11:01:32.938 DebugLog[12085:807] Hello, World!
  // With DebugLog
  Hello, World!
  Hello, World!
</pre>
<p>NSLog() includes the time, process name, process id and thread id as a prefix on every message.  I find this excessive in most cases, but you can add it in if you wish.  More on this later.</p>
<p>In the next version of the project, disable the function except for Debug builds.  Do this by editing DebugLog.h to have an #ifdef that turns DebugLog() into a macro, and rename the function from DebugLog to _DebugLog.  By using a #else we can disable DebugLog for any non DEBUG builds.</p>
<pre>
  #ifdef DEBUG
  #define DebugLog(args...) _DebugLog(args);
  #else
  #define DebugLog(x...)
  #endif
  void _DebugLog(NSString *format,...);
</pre>
<p>Rename the function in DebugLog.m as well.</p>
<pre>
  void _DebugLog(NSString *format,...) {
</pre>
<p>Finally, setup the build settings to include a DEBUG flag.  For more deatil or for iPhone configurations, see the <a href="http://iphoneincubator.com/blog/debugging/how-to-create-conditional-log-statements-in-xcode">the post that inspired this one.</a></p>
<p><img src="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-002.png" alt="DebugLog_002.png" border="0" width="250" height="300" /></p>
<p>Now try building both the Debug and Release version. Run from the command line, only the Debug version will produce the debug lines</p>
<pre>
  <strong>explorer:karl/tmp/DebugLog%</strong>./build/Debug/DebugLog
  Hello, World!
  <strong>explorer:karl/tmp/DebugLog%</strong>./build/Release/DebugLog
  <strong>explorer:karl/tmp/DebugLog%</strong>
</pre>
<p>Again, you can <a href="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-002.zip" title="DebugLog_002.zip">download the project at this stage</a>.  </p>
<p>Now take the function from better to best. By using some preprocessor directives we can embed the name of the file and line number where the DebugLog() is called, or have it print a function or method name.  </p>
<p>Change the macro definition and function declaration:</p>
<pre>
  #ifdef DEBUG
  #define DebugLog(args...) _DebugLog(__FILE__,__LINE__,args);
  #else
  #define DebugLog(x...)
  #endif
  void _DebugLog(const char *file, int lineNumber, NSString *format,...);
</pre>
<p>and change the fprintf() in the implementation to print the passed arguments:</p>
<pre>
  fprintf(stderr,"%s:%d %s",file,lineNumber,[body UTF8String]);
</pre>
<p>The output will now look like this:</p>
<pre>
  /Users/karl/tmp/DebugLog/main.m:15 Hello, World!
</pre>
<p>The __FILE__ is expanded to the complete path to the file, which is usually more verbose that I need.  It can be trimmed down to the actual file name by using an NSString method:</p>
<pre>
  ...
  NSString *fileName=[[NSString stringWithUTF8String:file] lastPathComponent];
  fprintf(stderr,"%s:%d %s",[fileName UTF8String],lineNumber,[body UTF8String]);
  ...
</pre>
<p>This will produce this output:</p>
<pre>
  main.m 15 Hello, World!
</pre>
<p></a>Again, you can <a href="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-003.zip" title="DebugLog_003.zip">download the project at this stage</a>.  </p>
<p>Finally, here is a more tricked out version that prints the function or method name instead of the file name, and prints the name of the thread.</p>
<pre>
  <strong>explorer:karl/tmp/DebugLog%</strong>./build/Debug/DebugLog
  MainThread/main (main.m:16) Hello, World!
  MainThread/+[SampleClass debugExample] (SampleClass.m:16) A sample debug message
  MainThread/-[SampleClass debugExample] (SampleClass.m:21) Another sample debug message
</pre>
<p>The final project <a href="http://www.karlkraft.com/wp-content/uploads/2009/03/debuglog-004.zip" title="DebugLog_004.zip">can be downloaded here</a>.  Stick the #import into your prefix header, and you can liberally sprinkle DebugLog commands all over your code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.karlkraft.com/index.php/2009/03/23/114/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dual Monitor Screen Savers</title>
		<link>http://www.karlkraft.com/index.php/2008/04/23/dual-monitor-screen-savers/</link>
		<comments>http://www.karlkraft.com/index.php/2008/04/23/dual-monitor-screen-savers/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 07:07:00 +0000</pubDate>
		<dc:creator>Karl Kraft</dc:creator>
				<category><![CDATA[TheCodeBook - Snippets]]></category>

		<guid isPermaLink="false">http://www.karlkraft.com/?p=52</guid>
		<description><![CDATA[How to create an OSX screen saver that works cooperatively across multiple monitors.]]></description>
			<content:encoded><![CDATA[<p>One of the things I find disappointing about OSX screensavers is that 95% of them don&#8217;t treat dual or triple monitor setups as one large area.  Instead they will either draw on the main screen only, or just run a separate instance for each monitor.  This makes it look like I have two or three separate computers instead of one large workspace.<br />
<span id="more-52"></span></p>
<p>The Desktop &#038; Screen Saver module in Preferences in has an option for &#8220;Main Screen Only&#8221;, in part to make the ugly look bearable, and in part because some screen savers have a nasty habit of never being tested on multiple monitor setups and crashing when running under that configuration.</p>
<p>To help put an end to this, I ported WanderingPolygon, a ScreenSaver that I wrote for NeXTSTEP in 1991 to run as a true &#8220;multiple monitor&#8221; screen saver.  A 3 to 9 sided polygon wanders across all your monitors, while cycling through a smooth ribbon of colors.  While I have only been able to test on a dual monitor setup, it should be able to deal correctly with any arrangement of one or more monitors.  I even tested it with non-contigous monitor setups.</p>
<p><img src="http://www.karlkraft.com/wp-content/uploads/2008/04/system-preferencesscreensnapz001.jpg" alt="System PreferencesScreenSnapz001.jpg" border="0" width="362" height="273" /></p>
<p>The source for the screen saver can be downloaded as  zip file (<a href="http://www.karlkraft.com/wp-content/uploads/2008/04/wanderingpolygon2.zip" title="WanderingPolygon.zip">WanderingPolygon.zip</a>).  The source includes the orginal 1991 release as well. When I get a moment I&#8217;ll add it to the public SVN repository.</p>
<p>If you want to just download the binary module, you can download that as a zip file as well (<a href="http://www.karlkraft.com/wp-content/uploads/2008/04/wanderingpolygonsaver2.zip" title="WanderingPolygon.saver.zip">WanderingPolygon.saver.zip</a>)</p>
<p>The source was pounded out in just an hour or so, most of which was spent running through various test scenarios, so it isn&#8217;t particularly pretty, and there are no configurable options except through recompiling,  but it should be easy ti figure out how to adapt this for other screen savers.  In the next day or so I hope to write  a more thorough technical description for those interested in developing multiple monitor savers.</p>
<p>If you have any questions in the mean time, you can drop me an email at <a href="mailto:karl@karlkraft.com">karl@karlkraft.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.karlkraft.com/index.php/2008/04/23/dual-monitor-screen-savers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Finding new files</title>
		<link>http://www.karlkraft.com/index.php/2008/01/03/finding-new-files/</link>
		<comments>http://www.karlkraft.com/index.php/2008/01/03/finding-new-files/#comments</comments>
		<pubDate>Thu, 03 Jan 2008 20:18:01 +0000</pubDate>
		<dc:creator>Karl Kraft</dc:creator>
				<category><![CDATA[TheCodeBook - Snippets]]></category>

		<guid isPermaLink="false">http://www.karlkraft.com/index.php/2008/01/03/finding-new-files/</guid>
		<description><![CDATA[This isn&#8217;t so much code as a useful command line trick for finding where a program is storing information. A fellow programmer needed to find where crontab entries were stored so I showed him this trick. If you need to know where an application is saving state you can follow this simple 3 step process. [...]]]></description>
			<content:encoded><![CDATA[<p>This isn&#8217;t so much code as a useful command line trick for finding where a program is storing information.<br />
<span id="more-12"></span></p>
<p>A fellow programmer needed to find where crontab entries were stored so I showed him this trick.  If you need to know where an application is saving state you can follow this simple 3 step process.</p>
<p>Create a file using touch. In this example the file is called TIMESTAMP.</p>
<pre>touch TIMESTAMP
</pre>
<p>Now go about the process of running the application. In his case he edited his crontab entries:</p>
<pre>crontab -e</pre>
<p>You can then find every file on your hard drive that was modified after the TIMESTAMP file with this command:</p>
<pre>find / -newer TIMESTAMP
</pre>
<p>If you are pretty sure that the data would need to be somewhere underneath your home directory you can use this alternative:</p>
<pre>find ~ -newer TIMESTAMP
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.karlkraft.com/index.php/2008/01/03/finding-new-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NSDrawNinePartImage</title>
		<link>http://www.karlkraft.com/index.php/2007/11/14/nsdrawninepartimage/</link>
		<comments>http://www.karlkraft.com/index.php/2007/11/14/nsdrawninepartimage/#comments</comments>
		<pubDate>Thu, 15 Nov 2007 01:28:00 +0000</pubDate>
		<dc:creator>Karl Kraft</dc:creator>
				<category><![CDATA[TheCodeBook - Snippets]]></category>

		<guid isPermaLink="false">http://www.karlkraft.com/index.php/2007/11/14/nsdrawninepartimage/</guid>
		<description><![CDATA[There is a cool new function in Leopard for drawing scaled rectangles of arbitrary width and height that keeps the corner and sides properly scaled while growing the center. Unfortunately there is no documentation, and when I last looked a whopping 3 google hits for the function name. This should make it number four. If [...]]]></description>
			<content:encoded><![CDATA[<p>There is a  cool new function in Leopard for drawing scaled rectangles of arbitrary width and height that keeps the corner and sides properly scaled while growing the center.</p>
<p>Unfortunately there is no documentation, and when I last looked a whopping 3 google hits for the function name.  This should make it number four.</p>
<p><span id="more-22"></span></p>
<p>If you want to draw a well or button in a view is to start with a bitmap image the same size as your view.  But what to do if you want to write a reusable class that can work at any size?  And how to deal with resolution independence?</p>
<p>NSDrawNinePartImage solves the problem.  To use it you create a 3&#215;3 matrix of images. You can either create them independently, or just draw a single image in PhotoShop and then break it apart in code.</p>
<p>Here is some sample code that appears in the OneMinuteEggTimer example application that is used for demonstrating the sound picker.</p>
<p><img src="http://www.karlkraft.com/wp-content/uploads/2008/01/24x24.gif" alt="24x24.gif" border="0" width="72" height="72" align="right" /></p>
<p>Start with the sample image.  In this case the image in 24&#215;24 pixels, but I&#8217;ve blown the image up to make it clearer what is going on.</p>
<p></p>
<p><img src="http://www.karlkraft.com/wp-content/uploads/2008/01/32x32.gif" alt="32x32.gif" border="0" width="96" height="96" align="right" /></p>
<p>The first step is to break the image into a 3&#215;3 matrix.  The corners will be drawn as is, the sides will each be tiled in one dimension, and the center will be tiled in two dimensions.  You can either break it using Photoshop, or programatically when your class is first used.</p>
<p>The +initialize method is called the first time your view class is referenced.  This is a function of the Objective-C runtime.  This code will take an image named SoundPickerBackground, and break it into 9 8&#215;8 tiles.</p>
<pre>

static NSImage *topLeftCornerImage;
static NSImage *topEdgeImage;
static NSImage *topRightCornerImage;
static NSImage *leftEdgeImage;
static NSImage *centerImage;
static NSImage *rightEdgeImage;
static NSImage *bottomLeftCornerImage;
static NSImage *bottomEdgeImage;
static NSImage *bottomRightCornerImage;

+ (void)initialize;
{
  if (baseImage) return;

  NSRect tileRect = NSMakeRect(0,0,8,8);

  baseImage = [NSImage imageNamed:@"SoundPickerBackground"];

  topLeftCornerImage = [[NSImage alloc] initWithSize:tileRect.size];
  [topLeftCornerImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(0.0,16.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [topLeftCornerImage unlockFocus];

  topEdgeImage = [[NSImage alloc] initWithSize:tileRect.size];
  [topEdgeImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(8.0,16.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [topEdgeImage unlockFocus];

  topRightCornerImage = [[NSImage alloc] initWithSize:tileRect.size];
  [topRightCornerImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(16.0,16.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [topRightCornerImage unlockFocus];

  leftEdgeImage = [[NSImage alloc] initWithSize:tileRect.size];
  [leftEdgeImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(0,8.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [leftEdgeImage unlockFocus];

  centerImage = [[NSImage alloc] initWithSize:tileRect.size];
  [centerImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(8.0,8.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [centerImage unlockFocus];

  rightEdgeImage = [[NSImage alloc] initWithSize:tileRect.size];
  [rightEdgeImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(16.0,8.0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [rightEdgeImage unlockFocus];

  bottomLeftCornerImage = [[NSImage alloc] initWithSize:tileRect.size];
  [bottomLeftCornerImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(0,0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [bottomLeftCornerImage unlockFocus];

  bottomEdgeImage = [[NSImage alloc] initWithSize:tileRect.size];
  [bottomEdgeImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(8.0,0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [bottomEdgeImage unlockFocus];

  bottomRightCornerImage = [[NSImage alloc] initWithSize:tileRect.size];
  [bottomRightCornerImage lockFocus];
  [baseImage drawInRect:tileRect
               fromRect:NSMakeRect(16.0,0,8.0,8.0)
              operation:NSCompositeCopy fraction:1.0];
  [bottomRightCornerImage unlockFocus];
}
</pre>
<p>Now when you need to draw the nine tiles, you simple call NSDrawNinePartImage in drawRect:</p>
<pre>- (void)drawRect:(NSRect)rect;
{
  NSDrawNinePartImage([self bounds],
                      topLeftCornerImage, topEdgeImage, topRightCornerImage,
                      leftEdgeImage, centerImage, rightEdgeImage,
                      bottomLeftCornerImage, bottomEdgeImage, bottomRightCornerImage,
                      NSCompositeSourceOver, 1.0, NO);
}
</pre>
<p>Drawn as 48&#215;48</p>
<div style="text-align:center;"><img src="http://www.karlkraft.com/wp-content/uploads/2008/01/48x48.gif" alt="48x48.gif" border="0" width="48" height="48" /></div>
<p>Drawn as 128&#215;128</p>
<div style="text-align:center;"><img src="http://www.karlkraft.com/wp-content/uploads/2008/01/128x128.gif" alt="128x128.gif" border="0" width="128" height="128" /></div>
]]></content:encoded>
			<wfw:commentRss>http://www.karlkraft.com/index.php/2007/11/14/nsdrawninepartimage/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QLog()</title>
		<link>http://www.karlkraft.com/index.php/2007/06/12/qlog/</link>
		<comments>http://www.karlkraft.com/index.php/2007/06/12/qlog/#comments</comments>
		<pubDate>Tue, 12 Jun 2007 05:40:55 +0000</pubDate>
		<dc:creator>Karl Kraft</dc:creator>
				<category><![CDATA[TheCodeBook - Snippets]]></category>

		<guid isPermaLink="false">http://www.karlkraft.com/index.php/2007/06/26/hello-world/</guid>
		<description><![CDATA[This Snippet is an alternative to NSLog. NSLog is great for occasional logging of debug and status message. It can however be a bit verbose because it includes the timestamp, process name, and process id on every line. If you are writing a command line tool this is overkill.QLog removes all this extra information and [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.karlkraft.com/wp-content/uploads/2007/06/qlog.zip">This Snippet</a> is an alternative to NSLog.  NSLog is great for occasional logging of debug and status message. It can however be a bit verbose because it includes  the timestamp, process name, and process id on every line.  If you are writing a command line tool this is overkill.QLog removes all this extra information and just prints the passed string and arguments.<br />
<span id="more-1"></span></p>
<p>
<code><br />
// Example<br />
NSLog(@"Starting %d",1);<br />
// 2007-06-26 01:39:35.629 MyGreatApp[3106:813] Starting 1<br />
QLog(@"Starting %d",1);<br />
// Starting 1<br />
</code></p>
<p>
As a bonus you can also redirect the output of QLog to a file by using setDebugOutputPath()
<p>
<code>void setDebugOutputPath(NSString *filePath)</code>
<p>
Note that filePath is not overwritten but rather appends new debug lines.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.karlkraft.com/index.php/2007/06/12/qlog/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
