<?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>Chris-Software.com &#187; Dev Center</title>
	<atom:link href="http://chris-software.com/index.php/category/dev-center/feed/" rel="self" type="application/rss+xml" />
	<link>http://chris-software.com</link>
	<description>iPhone, iPod touch games, Objective-C Tutorials, krzysztofrutkowski.com</description>
	<lastBuildDate>Tue, 29 Mar 2011 09:58:11 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>How to install apps on devices without certificate</title>
		<link>http://chris-software.com/index.php/2009/09/28/how-to-install-apps-on-devices-without-certificate/</link>
		<comments>http://chris-software.com/index.php/2009/09/28/how-to-install-apps-on-devices-without-certificate/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 16:14:16 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[SDK Tools]]></category>
		<category><![CDATA[apps]]></category>
		<category><![CDATA[how to install apps on devices without certificate]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[installing on device]]></category>
		<category><![CDATA[no cerificate]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=933</guid>
		<description><![CDATA[As you know to distribute the applications in App Store or even to debug them on real device according to Apple you have to pay $99 to achieve the provisiong and distribution certificate.
But of course as you know, there are always other ways to achieve the similar result. But 1st. your device has to be [...]]]></description>
			<content:encoded><![CDATA[<p>As you know to distribute the applications in App Store or even to debug them on real device according to Apple you have to pay $99 to achieve the provisiong and distribution certificate.</p>
<p>But of course as you know, there are always other ways to achieve the similar result. But 1st. your device has to be jailbroken and 2nd. you can distribute your app only among jailbroken devices via Cydia, Icy or less friendly through SSH. It has advantages and disadvantage. Not all iPhones and iPod touches are jailbroken (I guess maybe 10% are), but you don&#8217;t have to obey the rules from Apple about submitted apps and you don&#8217;t have to wait at least one week for the review result.</p>
<h2>Tasks you need to do only once (for developer):</h2>
<ol>
<li>Jailbreak your iPhone</li>
<li>Install LDID (Link Identity Editor), Mobile Termial and OpenSSH from Cydia</li>
<li>Go to /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/<strong>iPhoneOS3.sdk</strong>/<br />
I personally tested in on 3.0 that&#8217;s why I put that in bold, if you are going to built your app on a higher SDK, go to the appropriate directory.</li>
<li>Open the SDKSettings.plist in your favorite editor (I recommend Property List Editor in Utilities) and in <em>Root</em> -&gt; <em>DefaultProperties</em> set <em>CODE_SIGNING_REQUIRED</em> = <strong>NO</strong>. BTW check if <em>AD_HOC_CODE_SIGNING_ALLOWED</em> equals <strong>NO</strong> and <em>CODE_SIGNING_ENTITLEMENTS</em> is blank.</li>
<li>Save the file.</li>
</ol>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/09/sdksettings.png"><img class="size-full wp-image-934 aligncenter" title="sdksettings" src="http://chris-software.com/wp-content/uploads/2009/09/sdksettings.png" alt="sdksettings" width="534" height="429" /></a></p>
<p>Please remember: modification of above .plist file simply allows you to build the package without signing it, so from now, you are able both to built package for Cydia and AppStore submission. Of course for App Store submission you provide a Distribution profile, for Cydia &#8220;Don&#8217;t Code Sign&#8221; in your project info under <strong>Build</strong>, <em>Code Signing</em>, <em>Code Signing Identity</em>, <em>Any iPhone OS Device</em>.</p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/09/build.png"><img class="alignnone size-full wp-image-935" title="build" src="http://chris-software.com/wp-content/uploads/2009/09/build.png" alt="build" width="518" height="407" /></a></p>
<h2>Tasks you need to do for every package (developer):</h2>
<ol>
<li>Build your project without signing it (Don&#8217;t Code Sign).</li>
<li>SSH your bundle to <strong>/Applications</strong> on your device. You can use Fugu for Mac or  WinSCP for Windows.</li>
<li>Now you have to fake-sign it to make it working. Open Mobile Terminal and type:<br />
su root<br />
you will be asked for password, by default: <strong>alpine</strong>. Next:<br />
<strong>ldid -S /Applications/My\ Project\ Name.app/My\ Project\ Name<br />
<span style="font-weight: normal;">make sure every space in name comes with the backslash before</span></strong></li>
<li><strong><span style="font-weight: normal;">If any error occurs, it means that you have provided wrong file path or didn&#8217;t built it with &#8220;Don&#8217;t Code Sign&#8221;.</span></strong></li>
<li>Now you can test your application, how it works on real device with full touch control, accelerometer and device&#8217;s performance, it&#8217;s really different from the Simulator.</li>
<li>If everything works correctly download the file that you modified with <strong>ldid</strong> &#8211; it&#8217;s the file named exactly the same as your project without any extensions, and replace it with original from your bundle.</li>
<li>Now you can distribute it in your own way.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/09/28/how-to-install-apps-on-devices-without-certificate/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		</item>
		<item>
		<title>Creating a nice glass buttons</title>
		<link>http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/</link>
		<comments>http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/#comments</comments>
		<pubDate>Tue, 12 May 2009 23:09:20 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[Button]]></category>
		<category><![CDATA[Glass]]></category>
		<category><![CDATA[UIButton]]></category>
		<category><![CDATA[UISegmentedControl]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=869</guid>
		<description><![CDATA[You can easily create buttons, link actions to them, but they aren&#8217;t cool at all.
This is the typical button:

And when being pressed (highlighted):

In my opinion rounded corners look nice, so do the highlighted version, but this white background doesn&#8217;t appeal to me. Open the Clock application and go to the Stopwatch. Don&#8217;t you think that these [...]]]></description>
			<content:encoded><![CDATA[<p>You can easily create buttons, link actions to them, but they aren&#8217;t cool at all.</p>
<p>This is the typical button:<br />
<img class="alignnone size-full wp-image-872" title="buttonnormal" src="http://chris-software.com/wp-content/uploads/2009/05/buttonnormal.png" alt="buttonnormal" width="130" height="53" /></p>
<p>And when being pressed (highlighted):<br />
<img class="alignnone size-full wp-image-871" title="buttonhighlighted" src="http://chris-software.com/wp-content/uploads/2009/05/buttonhighlighted.png" alt="buttonhighlighted" width="131" height="48" /></p>
<p><img class="size-medium wp-image-873 alignleft" style="margin-left: 10px; margin-right: 10px; margin-top: 0px; margin-bottom: 5px;" title="stopwatchbutton" src="http://chris-software.com/wp-content/uploads/2009/05/stopwatchbutton-200x300.png" alt="stopwatchbutton" width="200" height="300" />In my opinion rounded corners look nice, so do the highlighted version, but this white background doesn&#8217;t appeal to me. Open the <strong>Clock</strong> application and go to the <strong>Stopwatch</strong>. Don&#8217;t you think that these <strong>Start/Stop</strong> and <strong>Reset/Lap</strong> buttons are more acceptable? Yes, they are.</p>
<p>You might have noticed that using <em>Interface Builder</em> you can set the <em>background color</em> of <em>UIButton</em>. Exacly. Below you can see the button with green background:<br />
<img class="alignnone size-full wp-image-870" title="buttonbackground" src="http://chris-software.com/wp-content/uploads/2009/05/buttonbackground.png" alt="buttonbackground" width="132" height="56" /></p>
<p>That&#8217;s it. <em>UIButton</em> has the <em>green background color</em>. Thank you very much and read my next tutorial.</p>
<p>Oh, sorry for the irony. So, in the case above, button looks like a TV from &#8217;90s rather than a green button. There is a simple way to achieve results similar to the <strong>Stopwatch</strong> application. All you have to do is to get rid of <em>UIButton</em> and use <em>UISegmentedControl</em>.</p>
<p><em>UISegmentedControl</em> is typicaly used in options / settings views, where you are able to pick one option of many.</p>
<p>Today, I&#8217;m going to show you how to customize this <em>UISegmentedControl</em>:<br />
<img class="alignnone size-full wp-image-874" title="segmentedcontrol" src="http://chris-software.com/wp-content/uploads/2009/05/segmentedcontrol.png" alt="segmentedcontrol" width="233" height="55" /></p>
<p>so it will look like this nice button below:<br />
<img class="alignnone size-full wp-image-875" title="segmentedcontrolbutton" src="http://chris-software.com/wp-content/uploads/2009/05/segmentedcontrolbutton.png" alt="segmentedcontrolbutton" width="223" height="44" /></p>
<p>Unfortunately you cannot do everything in <em>Interface Builder</em> only, so you will need to create an <em>IBOutlet</em> and connect it to created <em>UISegmentedControl</em> in <em>Interface Builder</em>.</p>
<pre>IBOutlet UISegmentedControl *myShinyButton;</pre>
<p>In <em>Interface Builder</em> go to <em>UISegmentedControl&#8217;s attributes</em>, and set <em>Segments=1</em> &#8211; so your <em>UISegmentedControl</em> will consist of only one segment &#8211; button. Check <em>momentary</em> &#8211; as you see on above <em>UISegmentedControl</em> example (First | Second), <strong>First</strong> is selected an it stays in that state until you select <strong>Second</strong>. Once <em>momentary</em> is checked the segment returns to the normal state after a second. Change the style to <em>Bar</em> &#8211; only <em>bar</em> can be customized in the way I want to show you. And the last thing you need to do: uncheck the <em>selected</em> for the current segment. Double click the button to type your own text on it. Your button should look like this:</p>
<p><img class="alignnone size-full wp-image-876" title="uisegmentedcontrolfirststate" src="http://chris-software.com/wp-content/uploads/2009/05/uisegmentedcontrolfirststate.png" alt="uisegmentedcontrolfirststate" width="163" height="48" /></p>
<p>Now you can customize the color, but you can only do it in <em>Xcode</em>. Use the property <em>tintColor</em>:</p>
<pre>myShinyButton.tintColor = [UIColor darkGrayColor];</pre>
<p>Here is how your button will look like after it:</p>
<p><img class="alignnone size-full wp-image-877" title="mybuttondarkgray" src="http://chris-software.com/wp-content/uploads/2009/05/mybuttondarkgray.png" alt="mybuttondarkgray" width="163" height="45" /></p>
<p><strong>Please note:</strong> avoid setting &#8220;strong colors&#8221; as a <em>tintColor</em>. Otherwise there will be no visible difference between normal and selected state when the color becomes more intensive. <em>darkGrayColor</em> will be perfect replacement of <em>blackColor</em>. You can also play with setting <em>RGB</em> colors where you have full control of intesitivity of red, green and blue.</p>
<h2>Programmatically</h2>
<pre><span><span>	</span></span><span>codeButton</span><span> = [[</span><span>UISegmentedControl</span><span> </span>alloc<span>] </span>initWithItems<span>:[</span><span>NSArray</span><span> </span>arrayWithObject<span>:</span><span>@"My Button"</span><span>]];
<span>	</span><span>codeButton</span>.segmentedControlStyle = <span>UISegmentedControlStyleBar</span>;
<span>	</span><span>codeButton</span>.momentary = <span>YES</span>;
<span>	</span><span>codeButton</span>.tintColor = [<span>UIColor</span> <span>lightGrayColor</span>];
<span>	</span><span>codeButton</span>.center = <span>CGPointMake</span>(<span>160</span>,<span>400</span>);
<span>	</span>[<span>self</span>.view <span>addSubview</span>:<span>codeButton</span>];</span></pre>
<h3>Please note:</h3>
<p>It won&#8217;t be discussed with details here, but remember, you can always use an <em>image</em> as a button (<em>UIButton</em> type: <em>custom</em>). Simple code:</p>
<pre><span><span>	</span>[button </span>setImage<span>:[</span><span>UIImage</span><span> </span>imageNamed<span>:</span><span>@"myButton.png"</span><span>] </span>forState<span>:</span>UIControlStateNormal<span>];
<span><span>	</span>[button </span>setImage<span>:[</span><span>UIImage</span><span> </span>imageNamed<span>:</span><span>@"myButton_highlighted.png"</span><span>] </span>forState<span>:</span>UIControlStateHighlighted<span>];
<span><span>	</span>[button </span>setImage<span>:[</span><span>UIImage</span><span> </span>imageNamed<span>:</span><span>@"myButton_selected.png"</span><span>] </span>forState<span>:</span>UIControlStateSelected<span>];</span></span></span></pre>
<p>Providing the right images will give you any effect you need.</p>
<h2>Actions</h2>
<p>To link any action to buttons created with <em>UISegmentedControl</em> use a <em>value changed</em> event instead of <em>Touch Up Inside</em>. In <em>Interface Builder</em> it should be quite easy, but to do it programmatically:</p>
<pre><span><span>	</span>[</span><span>codeButton</span><span> </span>addTarget<span>:</span><span>self</span><span> </span>action<span>:</span><span>@selector</span><span>(</span><span>simpleAction</span><span>) </span>forControlEvents<span>:</span>UIControlEventValueChanged<span>];</span></pre>
<p>As usuall, sample project for you:</p>
<p style="text-align: center;"><img class="size-medium wp-image-879 aligncenter" title="glassbuttonssimulator" src="http://chris-software.com/wp-content/uploads/2009/05/glassbuttonssimulator-161x300.png" alt="glassbuttonssimulator" width="161" height="300" /></p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/glassbutton.zip"><img class="size-full wp-image-564 aligncenter" title="xcodeproj" src="http://chris-software.com/wp-content/uploads/2009/04/xcodeproj.png" alt="xcodeproj" width="128" height="128" /></a></p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/glassbutton.zip">Download the project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Playing backgroud music</title>
		<link>http://chris-software.com/index.php/2009/05/09/playing-backgroud-music/</link>
		<comments>http://chris-software.com/index.php/2009/05/09/playing-backgroud-music/#comments</comments>
		<pubDate>Sat, 09 May 2009 17:39:08 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[fade]]></category>
		<category><![CDATA[loop]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[play music]]></category>
		<category><![CDATA[Playing background music]]></category>
		<category><![CDATA[the volume]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=849</guid>
		<description><![CDATA[Related tutorials:

Short sounds

I&#8217;ve already told you how to play short sounds in your game / application. Now it&#8217;s time to play some music in the background. Although using one type of short sounds , doesn&#8217;t stop the iPod playback, adding the background music will turn iPod off.
In fact using AVAudioPlayer you can also play background [...]]]></description>
			<content:encoded><![CDATA[<h3>Related tutorials:</h3>
<ul>
<li><a href="http://chris-software.com/index.php/2009/05/05/short-sounds/">Short sounds</a></li>
</ul>
<p>I&#8217;ve already told you how to play short sounds in your game / application. Now it&#8217;s time to play some music in the background. Although using one type of <em>short sounds</em> , doesn&#8217;t stop the iPod playback, adding the background music will turn iPod off.</p>
<p>In fact using <strong>AVAudioPlayer</strong> you can also play background music, so, in other words <strong>AVAudioPlayer</strong> can play longer sounds, not only those limited to 30 seconds. Here is the code again (remember to add a framework: <em>AVFoundation.framework</em>):</p>
<pre><span><span>	AVAudioPlayer *</span>my</span><span>AVsound</span><span> = [[</span><span>AVAudioPlayer</span><span> </span>alloc<span>] </span>initWithContentsOfURL<span>:[</span><span>NSURL</span><span> </span>fileURLWithPath<span>:[[</span><span>NSBundle</span><span> </span>mainBundle<span>] </span>pathForResource<span>:</span><span>@"<strong>backgroundMusic</strong>"</span><span> </span>ofType<span>:</span><span>@"<strong>caf</strong>"</span><span>]  ] </span>error<span>:</span><span>NULL</span><span>];
	[myAVsound play]; </span></pre>
<p>The above code will simply play the background music [<strong>backgroundMusic.caf</strong>]. <span style="text-decoration: underline;">But it will play it only once</span>. You could use <em>NSTimer</em> to play it several times &#8211; call <em>[myAVsound play]</em>.</p>
<h3>GBMusicTrack</h3>
<p>I would like to present you very nice class &#8211; <em>GBMusicTrack,</em> written by <strong>Jake Peterson</strong> (aka A<em>notherJake</em>). You can find more info <a href="http://groups.google.com/group/cocos2d-iphone-discuss/web/background-music-track-engine---gbmusictrack">here</a>. <strong>Please note</strong>, that you can play only one background music at time using this class, the second and any next track can be played, once you stopped playing the previous.</p>
<p><strong>GBMusicTrack.h</strong>:</p>
<pre dir="ltr">//
//  GBMusicTrack.h
//  GameBase
//
//  Created by Jake Peterson (AnotherJake) on 7/6/08.
//  Copyright 2008 Jake Peterson. All rights reserved.
//

#import &lt;UIKit/UIKit.h&gt; // <strong>IN ORIGINAL FILE &lt;Cocoa/Cocoa.h&gt;</strong>
#import &lt;AudioToolbox/AudioQueue.h&gt;
#import &lt;AudioToolbox/AudioFile.h&gt;

#define NUM_QUEUE_BUFFERS	3

@interface GBMusicTrack : NSObject
{
	AudioFileID						audioFile;
	AudioStreamBasicDescription		dataFormat;
	AudioQueueRef					queue;
	UInt64							packetIndex;
	UInt32							numPacketsToRead;
	AudioStreamPacketDescription	*packetDescs;
	BOOL							repeat;
	BOOL							trackClosed;
	AudioQueueBufferRef				buffers[NUM_QUEUE_BUFFERS];
}

- (id)initWithPath:(NSString *)path;
- (void)setGain:(Float32)gain;
- (void)setRepeat:(BOOL)yn;
- (void)play;
- (void)pause;

// close is called automatically in GBMusicTrack's dealloc method, but it is recommended
// to call close first, so that the associated Audio Queue is released immediately, instead
// of having to wait for a possible autorelease, which may cause some conflict
- (void)close;

extern NSString	*GBMusicTrackFinishedPlayingNotification;

@end</pre>
<p><strong>GBMusicTrack.m</strong></p>
<pre dir="ltr">//
//  GBMusicTrack.m
//  GameBase
//
//  Created by Jake Peterson (AnotherJake) on 7/6/08.
//  Copyright 2008 Jake Peterson. All rights reserved.
//

#import "GBMusicTrack.h"

static UInt32 gBufferSizeBytes = 0x10000; // 64k

NSString *GBMusicTrackFinishedPlayingNotification = @"GBMusicTrackFinishedPlayingNotification";

@interface GBMusicTrack (InternalMethods)

static void BufferCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef buffer);
- (void)callbackForBuffer:(AudioQueueBufferRef)buffer;
- (UInt32)readPacketsIntoBuffer:(AudioQueueBufferRef)buffer;

@end

@implementation GBMusicTrack

#pragma mark -
#pragma mark GBMusicTrack

- (void)dealloc
{
	[self close];
	[super dealloc];
}

- (void)close
{
	// it is preferrable to call close first, before dealloc if there is a problem waiting for
	// an autorelease
	if (trackClosed)
		return;
	trackClosed = YES;
	AudioQueueStop(queue, YES);
	AudioQueueDispose(queue, YES);
	AudioFileClose(audioFile);
}

- (id)initWithPath:(NSString *)path
{
	UInt32		size, maxPacketSize;
	char		*cookie;
	int			i;

	if(!(self = [super init])) return nil;
	if (path == nil) return nil;

	// try to open up the file using the specified path
	if (noErr != AudioFileOpenURL((CFURLRef)[NSURL fileURLWithPath:path], 0x01, kAudioFileCAFType, &amp;audioFile))
	{
		NSLog(@"GBMusicTrack Error - initWithPath: could not open audio file. Path given was: %@", path);
		return nil;
	}

	// get the data format of the file
	size = sizeof(dataFormat);
	AudioFileGetProperty(audioFile, kAudioFilePropertyDataFormat, &amp;size, &amp;dataFormat);

	// create a new playback queue using the specified data format and buffer callback
	AudioQueueNewOutput(&amp;dataFormat, BufferCallback, self, nil, nil, 0, &amp;queue);

	// calculate number of packets to read and allocate space for packet descriptions if needed
	if (dataFormat.mBytesPerPacket == 0 || dataFormat.mFramesPerPacket == 0)
	{
		// since we didn't get sizes to work with, then this must be VBR data (Variable BitRate), so
		// we'll have to ask Core Audio to give us a conservative estimate of the largest packet we are
		// likely to read with kAudioFilePropertyPacketSizeUpperBound
		size = sizeof(maxPacketSize);
		AudioFileGetProperty(audioFile, kAudioFilePropertyPacketSizeUpperBound, &amp;size, &amp;maxPacketSize);
		if (maxPacketSize &gt; gBufferSizeBytes)
		{
			// hmm... well, we don't want to go over our buffer size, so we'll have to limit it I guess
			maxPacketSize = gBufferSizeBytes;
			NSLog(@"GBMusicTrack Warning - initWithPath: had to limit packet size requested for file path: %@", path);
		}
		numPacketsToRead = gBufferSizeBytes / maxPacketSize;

		// will need a packet description for each packet since this is VBR data, so allocate space accordingly
		packetDescs = malloc(sizeof(AudioStreamPacketDescription) * numPacketsToRead);
	}
	else
	{
		// for CBR data (Constant BitRate), we can simply fill each buffer with as many packets as will fit
		numPacketsToRead = gBufferSizeBytes / dataFormat.mBytesPerPacket;

		// don't need packet descriptsions for CBR data
		packetDescs = nil;
	}

	// see if file uses a magic cookie (a magic cookie is meta data which some formats use)
	AudioFileGetPropertyInfo(audioFile, kAudioFilePropertyMagicCookieData, &amp;size, nil);
	if (size &gt; 0)
	{
		// copy the cookie data from the file into the audio queue
		cookie = malloc(sizeof(char) * size);
		AudioFileGetProperty(audioFile, kAudioFilePropertyMagicCookieData, &amp;size, cookie);
		AudioQueueSetProperty(queue, kAudioQueueProperty_MagicCookie, cookie, size);
		free(cookie);
	}

	// allocate and prime buffers with some data
	packetIndex = 0;
	for (i = 0; i &lt; NUM_QUEUE_BUFFERS; i++)
	{
		AudioQueueAllocateBuffer(queue, gBufferSizeBytes, &amp;buffers[i]);
		if ([self readPacketsIntoBuffer:buffers[i]] == 0)
		{
			// this might happen if the file was so short that it needed less buffers than we planned on using
			break;
		}
	}
	repeat = NO;
	trackClosed = NO;
	return self;
}

- (void)setGain:(Float32)gain
{
	AudioQueueSetParameter(queue, kAudioQueueParam_Volume, gain);
}

- (void)setRepeat:(BOOL)yn
{
	repeat = yn;
}

- (void)play
{
	AudioQueueStart(queue, nil);
}

- (void)pause
{
	AudioQueuePause(queue);
}

#pragma mark -
#pragma mark Callback

static void BufferCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef buffer)
{
	// redirect back to the class to handle it there instead, so we have direct access to the instance variables
	[(GBMusicTrack *)inUserData callbackForBuffer:buffer];
}

- (void)callbackForBuffer:(AudioQueueBufferRef)buffer
{
	if ([self readPacketsIntoBuffer:buffer] == 0)
	{
		// End Of File reached, so rewind and refill the buffer using the beginning of the file instead
		packetIndex = 0;
		[self readPacketsIntoBuffer:buffer];

		// if not repeating then we'll pause it so it's ready to play again immediately if needed
		if (!repeat)
		{
			AudioQueuePause(queue);

			// we're not in the main thread during this callback, so enqueue a message on the main thread to post notification
			// that we're done, or else the notification will have to be handled in this thread, making things more difficult
			[self performSelectorOnMainThread:@selector(postTrackFinishedPlayingNotification:) withObject:nil waitUntilDone:NO];
		}
	}
}

- (void)postTrackFinishedPlayingNotification:(id)object
{
	// if we're here then we're in the main thread as specified by the callback, so now we can post notification that
	// the track is done without the notification observer(s) having to worry about thread safety and autorelease pools
	[[NSNotificationCenter defaultCenter] postNotificationName:GBMusicTrackFinishedPlayingNotification object:self];
}

- (UInt32)readPacketsIntoBuffer:(AudioQueueBufferRef)buffer
{
	UInt32		numBytes, numPackets;

	// read packets into buffer from file
	numPackets = numPacketsToRead;
	AudioFileReadPackets(audioFile, NO, &amp;numBytes, packetDescs, packetIndex, &amp;numPackets, buffer-&gt;mAudioData);
	if (numPackets &gt; 0)
	{
		// - End Of File has not been reached yet since we read some packets, so enqueue the buffer we just read into
		// the audio queue, to be played next
		// - (packetDescs ? numPackets : 0) means that if there are packet descriptions (which are used only for Variable
		// BitRate data (VBR)) we'll have to send one for each packet, otherwise zero
		buffer-&gt;mAudioDataByteSize = numBytes;
		AudioQueueEnqueueBuffer(queue, buffer, (packetDescs ? numPackets : 0), packetDescs);

		// move ahead to be ready for next time we need to read from the file
		packetIndex += numPackets;
	}
	return numPackets;
}

@end</pre>
<p>If you don&#8217;t understand what every line of this code means, don&#8217;t worry. Here is the simple instruction how to use it:</p>
<pre dir="ltr">GBMusicTrack *backgroundMusic = [[GBMusicTrack alloc] initWithPath:[[NSBundle mainBundle] pathForResource:@"backgroundMusic" ofType:@"caf"]];
[backgroundMusic setRepeat:YES]; // or NO if you want to play it only once
[backgroundMusic setGain:1.0]; // volume
[backgroundMusic play];</pre>
<p>Remember to import not only <strong>GBMusicTrack.h</strong> to the class with above lines of code, but also to add <strong>AudiToolbox.framework</strong>. As you see using <em>GBMusicTrack</em> class is quite simple, <em>setRepeat:YES/NO</em> method allows you to decide if you want your music to loop constantly, <em>setGain</em> to adjust the volume (remember: try to avoid setting the volume louder than 1.0) and <em>play</em> to start playing.</p>
<p><strong>Please note:</strong> compile for the version <strong>2.2</strong> or higher!</p>
<p><strong>Please note:</strong> many people complains that anything from this tutorial doesn&#8217;t work on <strong>iPhone Simulator</strong>. Don&#8217;t worry, it works on real device.</p>
<h3>Playing the next track using <em>GBMusicTrack</em>:</h3>
<p>As I told before, this class allows you to play one track at the time. To play next, you have to call the <em>close</em> method and <em>initialize</em> it again:</p>
<pre>	[backgroundMusic close];
<span><span>	</span>[</span><span>backgroundMusic</span><span> </span>initWithPath<span>:[[</span><span>NSBundle</span><span> </span>mainBundle<span>] </span>pathForResource<span>:</span><span>@"nextTrack"</span><span> </span>ofType<span>:</span><span>@"caf"</span><span>]];</span></pre>
<p>You can download my sample project: &#8211; my music controller I&#8217;ve written using the <strong>GBMusicTrack</strong>. You can fade the music in / out, play and pause and set the volume.</p>
<p style="text-align: center; "><a href="http://chris-software.com/wp-content/uploads/2009/05/musiccontrollerscreenshot.png"><img class="alignnone size-medium wp-image-851" title="musiccontrollerscreenshot" src="http://chris-software.com/wp-content/uploads/2009/05/musiccontrollerscreenshot-200x300.png" alt="musiccontrollerscreenshot" width="200" height="300" /></a></p>
<p style="text-align: center; "><a href="http://chris-software.com/wp-content/uploads/2009/05/musiccontroller.zip"><img class="size-full wp-image-564 alignnone" title="xcodeproj" src="http://chris-software.com/wp-content/uploads/2009/04/xcodeproj.png" alt="xcodeproj" width="128" height="128" /></a></p>
<p style="text-align: center; "><a href="http://chris-software.com/wp-content/uploads/2009/05/musiccontroller.zip">Download the project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/09/playing-backgroud-music/feed/</wfw:commentRss>
		<slash:comments>39</slash:comments>
		</item>
		<item>
		<title>Creating programmatically a spinner (UIActivityIndicator)</title>
		<link>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-spinner-uiactivityindicator/</link>
		<comments>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-spinner-uiactivityindicator/#comments</comments>
		<pubDate>Fri, 08 May 2009 18:38:48 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[Creating programmatically a spinner]]></category>
		<category><![CDATA[Creating programmatically a spinner (UIActivityIndicator)]]></category>
		<category><![CDATA[spinner]]></category>
		<category><![CDATA[UIActivityIndicator]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=835</guid>
		<description><![CDATA[UIActivityIndicator commonly named Spinner is used usually to tell the user that some process is currently in progress.
There are three types of UIActivityIndicators:
 From the left: gray (UIActivityIndicatorViewStyleGray), white (UIActivityIndicatorViewStyleWhite) and large white (UIActivityIndicatorViewStyleWhiteLarge).
To allocate any of them use the following code:
	UIActivityIndicatorView *myIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]];
	myIndicator.center = CGPointMake(160, 240);
	myIndicator.hidesWhenStopped = NO;
As you see this [...]]]></description>
			<content:encoded><![CDATA[<p><em>UIActivityIndicator</em> commonly named <strong>Spinner</strong> is used usually to tell the user that some process is currently in progress.</p>
<p>There are three types of <em>UIActivityIndicators</em>:</p>
<p><a href="http://chris-software.com/wp-content/uploads/2009/05/activityindicators.png"><img class="size-full wp-image-836 alignleft" style="margin-top: 0px; margin-bottom: 5px; margin-left: 10px; margin-right: 10px;" title="activityindicators" src="http://chris-software.com/wp-content/uploads/2009/05/activityindicators.png" alt="activityindicators" width="114" height="45" /></a> From the left: <strong>gray</strong> (<em>UIActivityIndicatorViewStyleGray</em>), <strong>white</strong> (<em>UIActivityIndicatorViewStyleWhite</em>) and <strong>large white</strong> (<em>UIActivityIndicatorViewStyleWhiteLarge</em>).</p>
<p>To allocate any of them use the following code:</p>
<pre><span><span>	</span></span><span>UIActivityIndicatorView</span><span> *myIndicator = [[</span><span>UIActivityIndicatorView</span><span> </span>alloc<span>] </span>initWithActivityIndicatorStyle<span>:</span><strong>UIActivityIndicatorViewStyleWhiteLarge]</strong><span>];
<span>	</span>myIndicator.center = <span>CGPointMake</span>(<span>160</span>, <span>240</span>);
	myIndicator.hidesWhenStopped = <strong>NO</strong>;</span></pre>
<p>As you see this time you shouldn&#8217;t provide initWithFrame as long as large white style has got different dimensions then white (small) and gray. Instead, set its center point.</p>
<p>To add <em>UIActivityIndicator</em> to your view simple use <em>addSubview</em> method:</p>
<pre>
<pre><span>	[self.view addSubview:myIndicator];</span></pre>
</pre>
<p>By default, UIActivityIndicator displays a static image, what in most cases isn&#8217;t what you want. You can easily start and stop animating it by using two methods:</p>
<pre>
<pre><span>	[myIndicator startAnimating];
	[myIndicator stopAnimating]; </span></pre>
</pre>
<p><strong>Please note:</strong> the <em>hidesWhenStopped=YES</em> property causes the <em>UIActivityIndicator</em> disappear once you stopped animating it and appear again once you started animating.</p>
<p>If you need to know programatically what is the current state of <em>UIActivityIndicator</em>, you can use <em>isAnimating</em> property:</p>
<pre>if ([myIndicator isAnimating]) NSLog(@"animating");
else NSLog(@"not animating");</pre>
<h3><em>UIActivityIndicator</em> in status bar</h3>
<p><img class="alignleft size-full wp-image-846" style="margin-top: 0px; margin-bottom: 5px; margin-left: 10px; margin-right: 10px;" title="spinnerstatusbar" src="http://chris-software.com/wp-content/uploads/2009/05/spinnerstatusbar.png" alt="spinnerstatusbar" width="320" height="20" />To display a <em>UIActivityIndicator</em> use the <em>UIApplication&#8217;s property:</em> <em>networkActivityIndicatorVisible</em>.</p>
<pre><span>	</span>[<span>UIApplication</span> <span>sharedApplication</span>].networkActivityIndicatorVisible = <span>YES</span>;</pre>
<p>and to disable:</p>
<pre><span>	</span>[<span>UIApplication</span> <span>sharedApplication</span>].networkActivityIndicatorVisible = NO;</pre>
<p>That’s almost all about <em>UIActivityIndicator</em>. More can be found in <strong>UIActivityIndicator Class Reference</strong> in documentation.</p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-spinner-uiactivityindicator/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Creating programmatically a label (UILabel)</title>
		<link>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-label-uilabel/</link>
		<comments>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-label-uilabel/#comments</comments>
		<pubDate>Fri, 08 May 2009 16:36:51 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[UILabel]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=832</guid>
		<description><![CDATA[UILabel allows you to display a single line text, most of us think so. In fact it can be used to display multiple lines as well.
To create an UILabel programmaticaly, code:
	UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
To display a text within UILabel use:

	myLabel.text = @"Lorem...";

And of course to add UILabel to your view:
	[self.view [...]]]></description>
			<content:encoded><![CDATA[<p><em>UILabel</em> allows you to display a single line text, most of us think so. In fact it can be used to display multiple lines as well.</p>
<p>To create an<em> UILabel</em> programmaticaly, code:</p>
<pre><span>	</span><span>UILabel</span> *myLabel = [[<span>UILabel</span> <span>alloc</span>] <span>initWithFrame</span>:<span>CGRectMake</span>(<span>50</span>, <span>100</span>, <span>200</span>, <span>100</span>)];</pre>
<div>To display a text within <em>UILabel</em> use:</div>
<pre>
<pre><span>	</span>myLabel.text = @"Lorem...";</pre>
</pre>
<p>And of course to add <em>UILabel</em> to your view:</p>
<pre><span>	</span>[<span>self</span>.view <span>addSubview</span>:myLabel];</pre>
<p>By default <em>UILabel</em> has a white background, you can remove the background or change the color easily:</p>
<pre>	myLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];</pre>
<h3>Setting the font:</h3>
<pre>
<pre>	myLabel.font = [UIFont fontWithName:@"<strong>Zapfino</strong>" size: <strong>14.0</strong>];</pre>
</pre>
<p>You can easily get a list of available fonts and the preview of them, using the free application <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=285217489&amp;mt=8">Fonts!</a> by <a href="http://appengines.com/">AppEngines</a>. <em>UILabel</em> can display text in different color then black and shadows as well:</p>
<pre><span>	</span>myLabel.shadowColor = [<span>UIColor</span> <span>grayColor</span>];
<span>	</span>myLabel.shadowOffset = <span>CGSizeMake</span>(<span>1</span>,<span>1</span>);
	myLabel.textColor = [UIColor blueColor];</pre>
<p>Best effect you will obtain by setting a color using <em>RGB</em> while setting the <em>alpha</em> half transparent. <em>shadowOffset</em> gives you the ability to set the shadow&#8217;s angle.</p>
<p>By default text is horizontally aligned to the left, you can set it either to the right or to the center.</p>
<pre><span>	</span>myLabel.textAlignment = <span>UITextAlignmentRight</span>; // UITextAlignmentCenter, UITextAlignmentLeft</pre>
<h3>Text wrapping</h3>
<p>As I told you, <em>UILabel</em> can display multiple lines of text, and to achieve it you need to set two properties <em>lineBreakMode</em> and <em>numberOfLines</em>:</p>
<pre>	myLabel.lineBreakMode = UILineBreakModeWordWrap;
	myLabel.numberOfLines = 2; // 2 lines ; 0 - dynamical number of lines
	myLabel.text = @"Lorem ipsum dolor sit\namet...";</pre>
<p>That’s all about <em>UILabel</em>. More can be found in <strong>UILabel</strong><strong> Class Reference</strong> in documentation.</p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-label-uilabel/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>Creating programmatically a switch (UISwitch)</title>
		<link>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-switch-uiswitch/</link>
		<comments>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-switch-uiswitch/#comments</comments>
		<pubDate>Fri, 08 May 2009 16:03:30 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[Creating programmatically a switch]]></category>
		<category><![CDATA[Creating programmatically a switch (UISwitch)]]></category>
		<category><![CDATA[UI Switch]]></category>
		<category><![CDATA[UISwitch]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=830</guid>
		<description><![CDATA[UISwitch is one of the simplest structure of UIKit. To create it programmatically, code:
	UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(50, 100, 0, 0)];
Above line allocates an UISwitch and sets its frame. UISwitch has fixed dimensions (about 95 px long, 27px high), so you have to set the coordinates for top-left corner. Width and height are ignored, [...]]]></description>
			<content:encoded><![CDATA[<p><em>UISwitch</em> is one of the simplest structure of <em>UIKit</em>. To create it programmatically, code:</p>
<pre><span>	</span><span>UISwitch</span> *mySwitch = [[<span>UISwitch</span> <span>alloc</span>] <span>initWithFrame</span>:<span>CGRectMake</span>(<span><strong>50</strong></span>, <span><strong>100</strong></span>, 0, 0)];</pre>
<div>Above line allocates an <em>UISwitch</em> and sets its frame. <em>UISwitch</em> has fixed dimensions (about 95 px long, 27px high), so you have to set the coordinates for top-left corner. Width and height are ignored, you can&#8217;t make switch smaller or bigger by changing the frame.</div>
<p>To add it to your view you should use this code:</p>
<pre>	[<span>self</span>.view <span>addSubview</span>:mySwitch];</pre>
<p>Be default switch is set to <strong>Off</strong>. You are able to change it&#8217;s state programmaticaly using <em>setOn</em> method:</p>
<pre>	[mySwitch <span>setOn</span>:<span><strong>YES</strong></span> <span>animated</span>:<span><strong>YES</strong></span>];</pre>
<p>To switch it back to <em>Off</em> use:</p>
<pre>	[mySwitch <span>setOn</span>:<strong>NO</strong> <span>animated</span>:<span>YES</span>];</pre>
<p>In both above cases <em>UISwitch</em> changes it state with animation (<em>animated:YES</em>), use <em>animated:NO</em> to change state without animation.</p>
<p>To check <em>UISwitch</em> current state use <em>on</em> property, example:</p>
<pre><span><span>	</span></span><span>if</span><span> (</span><span>mySwitch</span><span>.on) </span><span>NSLog</span><span>(</span>@"switch state: on"<span>);
<span><span>	</span></span><span>else</span><span> </span><span>NSLog</span><span>(</span>@"switch state: off"<span>);</span></span></pre>
<p>To prevent changing the <em>UISwitch</em> state set the <em>enabled </em>property to <em>NO</em>:</p>
<pre>mySwitch.enabled = NO; // or YES to reenable it</pre>
<p>As I said before <em>UISwitch</em> is very simple structure &#8211; any action &#8211; touching it causes <em>UISwitch</em> to change it&#8217;s state, so to call any method by changing the <em>UISwitch</em> you have to add a target for <em>ValueChanged</em> event:</p>
<pre><span><span>	</span>[</span><span>mySwitch</span><span> </span>addTarget<span>:</span><span>self</span><span> </span>action<span>:</span><span>@selector</span><span>(<strong>myMethod</strong></span><span>) </span>forControlEvents<span>:</span>UIControlEventValueChanged<span>];</span></pre>
<div>or</div>
<pre><span><span>	</span>[</span><span>mySwitch</span><span> </span>addTarget<span>:</span><span>self</span><span> </span>action<span>:</span><span>@selector</span><span>(<strong>myMethod</strong><strong>:</strong></span><span>) </span>forControlEvents<span>:</span>UIControlEventValueChanged<span>];</span></pre>
<div>If you need a <em>id</em> to <em>mySwitch</em> object.</div>
<div>That&#8217;s all about <em>UISwitch</em>. More can be found in <strong>UISwitch Class Reference</strong> in documentation.</div>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/08/creating-programmatically-a-switch-uiswitch/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Planning a bigger application</title>
		<link>http://chris-software.com/index.php/2009/05/06/planning-a-bigger-application/</link>
		<comments>http://chris-software.com/index.php/2009/05/06/planning-a-bigger-application/#comments</comments>
		<pubDate>Tue, 05 May 2009 23:43:45 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[application]]></category>
		<category><![CDATA[big]]></category>
		<category><![CDATA[bigger applications]]></category>
		<category><![CDATA[navigate]]></category>
		<category><![CDATA[Planning bigger application]]></category>
		<category><![CDATA[start programming]]></category>
		<category><![CDATA[two views]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=816</guid>
		<description><![CDATA[Before you start developing a bigger application you should plan, how the whole project&#8217;s classes should talk to each other. You should take a sheet of paper and draw the schema, describing the most important classes
I don&#8217;t want you to draw the flowchart describing every single algorithm, every if statement or loop like this one below.

When [...]]]></description>
			<content:encoded><![CDATA[<p>Before you start developing a bigger application you should plan, how the whole project&#8217;s classes should talk to each other. You should take a sheet of paper and draw the schema, describing the most important classes</p>
<p>I don&#8217;t want you to draw the flowchart describing every single algorithm, every <em>if statement</em> or <em>loop</em> like this one below.</p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/flowcharts.png"><img class="alignnone size-medium wp-image-817" title="flowcharts" src="http://chris-software.com/wp-content/uploads/2009/05/flowcharts-163x300.png" alt="flowcharts" width="163" height="300" /></a></p>
<p style="text-align: left;">When I started programming, every next <em>view</em> (<em>UIViewController</em>) of any application, was <em>allocated</em> by previous <em>view</em> and there was no simple way to return from the last one to the first one. Either I had to start programming the app from the beginning to fix it or had to call <em>dealloc</em> method which should be called only automaticaly when the application is quited.</p>
<p style="text-align: left;">
<p style="text-align: left;">Since few months I&#8217;ve new idea, I would like to show you. Below is the schema &#8211; the frame of most my new apps:</p>
<p style="text-align: center;"><span style="color: #0000ee; text-decoration: underline;"><a href="http://chris-software.com/wp-content/uploads/2009/05/schema.png"></a><a href="http://chris-software.com/wp-content/uploads/2009/05/schema.png"><img class="size-full wp-image-819 aligncenter" title="schema" src="http://chris-software.com/wp-content/uploads/2009/05/schema.png" alt="schema" width="615" height="384" /></a></span></p>
<p style="text-align: left;">Legend:</p>
<p style="text-align: left;">
<ul>
<li><strong>A</strong> &#8211; App Delegate, the first objective-c file, autmatically allocated when the application starts.</li>
<li><strong>B</strong> &#8211; Main Controller &#8211; this is the &#8220;application central unit&#8221; that is responsible for displaying some part of the menu, receiving messages from any classes it allocates and delivering them somewhere else.</li>
<li><strong>C</strong> &#8211; Settings &#8211; class that provides an interface to adjust the volume of sounds / music, way of steering (arrows / accelerometer) etc.</li>
<li><strong>D</strong> &#8211; heart of the sounds and the background music.</li>
<li><strong>E</strong> &#8211; in this case, the funniest part of app, the hardest to code, responsible for loading a level, tracking the game progress, check for collisions and more.</li>
<li><strong>F</strong> &#8211; provides a form for entering new high score</li>
<li><strong>G</strong> &#8211; displays the best times / scores for any level.</li>
<li><strong>H</strong> &#8211; other simple <em>views</em> that almost every application has.</li>
</ul>
<h3>How does it all work?</h3>
<p>Let&#8217;s start with arrow <strong>#1</strong>. In fact, my <strong>App Delegate [A]</strong> has one single task - to allocate a next <em>view</em>, in this case the <strong>Main Controller [B]</strong> and I never use it again.</p>
<p>Once <strong>MainController [B]</strong> is allocated the <em>Main Menu</em> it provides is visible on the screen. Any function user presses is <em>allocated</em> and/or displayed via transition or not &#8211; it&#8217;s up to me.</p>
<p><strong>#2, #3, #9<br />
<span style="font-weight: normal;">When users changes the volume in the </span>Settings [C]</strong>, the <strong>Main Controller [B]</strong> is informed about that change and it&#8217;s passed to the <strong>Sound and Music Engine [D]</strong> to perform necessary tasks. If it was other option, for sure <strong>Main Controller [B]</strong> now, how to deal with it.</p>
<p><strong>#4, #5, #6<br />
<span style="font-weight: normal;">When users starts/load/continue the game,</span> Game Controller [E]</strong> is checking each parameter of the game. When the game is canceled it returns to <strong>Main Controller [B]</strong>, when the game is over, it checks, if the score is enough to appear on the high scores list. If yes it tells the <strong>Main Controller [B]</strong> to display the form &#8211; <strong>New High-Scores [F]</strong>. Once form was compleated, <strong>#6 Main Controller [B]</strong> updates the list of high scores and displays the records <strong>High-Scores View [G]</strong>.</p>
<p><strong>#7<br />
<span style="font-weight: normal;">User can easily visit the </span>High-Scores View [G]<span style="font-weight: normal;"> and quit to </span>Main Controller [B]<span style="font-weight: normal;"> without any difficulties.</span></strong></p>
<p><strong>#8<br />
<span style="font-weight: normal;">Any instructions, information are simply more or less polished <em>views</em>, so one class is enough to handle them all. It&#8217;s easy to navigate from </span>Main Controller [B]<span style="font-weight: normal;"> to </span>Others [H]<span style="font-weight: normal;"> and vice verse.</span></strong></p>
<p><strong>#9<br />
<span style="font-weight: normal;">Whatever user does in the application, </span>Main Controller [B] </strong>tells the <strong>Sound Engine [D]</strong>, if it should play a simple button pressed sound or change the background music.</p>
<p>I&#8217;ve just shown you my idea of programming bigger applications. Of course it doesn&#8217;t mean that whatever I do, is made with only eight classes. For example <strong>Game Controller</strong> has many other classes it includes to help him checking what is going on in the game and they talk only with <strong>Game Controller</strong> and it decides if it should send a message to <strong>Main Controller</strong> to finish the game or continue it.</p>
<p>Hope this helped.</p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/06/planning-a-bigger-application/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Tables</title>
		<link>http://chris-software.com/index.php/2009/05/05/tables/</link>
		<comments>http://chris-software.com/index.php/2009/05/05/tables/#comments</comments>
		<pubDate>Tue, 05 May 2009 19:26:42 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[table]]></category>
		<category><![CDATA[tables]]></category>
		<category><![CDATA[UITableView]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=780</guid>
		<description><![CDATA[Tables &#8211; strictly UITableView, are very often used in utilities, content managers, lists and more. There are many examples of tables in applications that came with every iPhone:

Phone application: Favourites, Recents, Contacts
SMS application: list of contacts you recently text messaged (not sure about the chat bubbles &#8211; it can be UIScrollView)
Calendar application: list of Calendars, List [...]]]></description>
			<content:encoded><![CDATA[<p>Tables &#8211; strictly <em>UITableView</em>, are very often used in <em>utilities</em>, content managers, lists and more. There are many examples of <em>tables</em> in applications that came with every iPhone:</p>
<ul>
<li>Phone application: <em>Favourites, Recents, Contacts</em></li>
<li>SMS application: list of contacts you recently text messaged (not sure about the chat bubbles &#8211; it can be <em>UIScrollView</em>)</li>
<li>Calendar application: list of Calendars, <em>List</em> view of selected calendar</li>
<li>Photos application: list of Photo Albums</li>
<li>YouTube application: every tab contains <em>UITableView</em></li>
<li>Weather application: flip-side view where you can add cities</li>
<li>Notes application: list of notes</li>
<li>Settings application: whole application</li>
<li>App Store application: every tab</li>
<li>Clock application: <em>World Clock, Alarm, Stopwatch</em></li>
<li><em>&#8230;</em></li>
</ul>
<p><img class="alignnone size-medium wp-image-781" title="tableview1" src="http://chris-software.com/wp-content/uploads/2009/05/tableview1-200x300.png" alt="tableview1" width="120" height="180" /> <img class="alignnone size-medium wp-image-782" title="tableview2" src="http://chris-software.com/wp-content/uploads/2009/05/tableview2-200x300.png" alt="tableview2" width="120" height="180" /> <img class="alignnone size-medium wp-image-783" title="tableview3" src="http://chris-software.com/wp-content/uploads/2009/05/tableview3-200x300.png" alt="tableview3" width="120" height="180" /> <img class="alignnone size-medium wp-image-784" title="tableview4" src="http://chris-software.com/wp-content/uploads/2009/05/tableview4-200x300.png" alt="tableview4" width="120" height="180" /> <img class="alignnone size-medium wp-image-785" title="tableview5" src="http://chris-software.com/wp-content/uploads/2009/05/tableview5-200x300.png" alt="tableview5" width="120" height="180" /></p>
<p>As you see <em>UITableView</em> is not only a white list with black text on it. <em>Table</em> (strictly <em>UITableViewCell</em>) can be customized in many ways, it can not only have many sections, headers, footers, edit and reorder functionality but even a custom <em>view</em>.</p>
<h2>Let&#8217;s start</h2>
<p>Create a <em>UIV</em><em>iewController</em> and <em>View XIB</em>. Name them all whatever you like (in my project I use: <strong>MyView.h</strong>, <strong>MyView.m</strong>, <strong>MyView.xib</strong>). In App Delegate add standard lines:</p>
<pre><span>#import </span>"MyView.h"

@class<span> </span><span>MyView</span><span>;</span></pre>
<p>and:</p>
<pre><span><span>	</span></span><span>MyView</span><span> *viewController = [[</span><span>MyView</span><span> </span>alloc<span>] </span>initWithNibName<span>:</span><span>@"MyView"</span><span> </span>bundle<span>:[</span><span>NSBundle</span><span> </span>mainBundle<span>]];
<span>	</span>[<span>window</span> <span>addSubview</span>:[viewController <span>view</span>]];</span></pre>
<p>Open <strong>MyView.xib</strong> and set that it&#8217;s class is <strong>MyView</strong>, add <em>UITableView and UIToolbar</em> or <em>UINavigationBar</em> on top &#8211; might be important later. The view should look like this:</p>
<p style="text-align: center; "><img class="alignnone size-medium wp-image-787" title="interfacetableprepare" src="http://chris-software.com/wp-content/uploads/2009/05/interfacetableprepare-206x299.png" alt="interfacetableprepare" width="206" height="299" /></p>
<p>Don&#8217;t close <em>Interface Builder</em> and edit <strong>MyView.h</strong> in <em>Xcode</em>. Add two protocols to <em>UIViewController</em>: <em>UITableViewDelegate</em> (responsible for a lot of actions with <em>tables</em>) and <em>UITableViewDataSource</em> (providing data to be displayed in the <em>table</em>). Add also an <em>IBOutlet</em> of <em>UITableView</em>. Although almost everything will be passed to <em>table</em> you created in <em>Interface Builder <span style="font-style: normal;">via</span> protocols,</em> but this object might be helpful in some cases I will discuss later.</p>
<p><strong>MyView.h</strong></p>
<pre><span>#import </span>&lt;UIKit/UIKit.h&gt;

<span>@interface</span> MyView : UIViewController &lt;UITableViewDelegate, UITableViewDataSource&gt; {
<span>	</span><span>IBOutlet</span> <span>UITableView</span> *myTable;
}

@end</pre>
<p>Compile your project and return to <em>Interface Builder</em> and make connections. <em>myTable</em> with <em>UITableView</em>, <em>view</em> with <em>View</em> and click on <em>UITableView</em> again, and in<em> Table View Connections</em>, connect <em>dataSource</em> and <em>delegate</em> with <em>File&#8217;s Owner</em>. Save <strong>MyView.xib</strong>.</p>
<p>Before you can debug your application you need to implement two method that are required to use <em>UITableView</em>:</p>
<ol>
<li><em>numberOfRowsInSection</em> &#8211; how many rows each section has</li>
<li><em>cellForRowAtIndexPath</em> &#8211; creates cells &#8211; <em>UITableViewCell</em></li>
</ol>
<p>So you need to implement above methods in your class:</p>
<pre>- (<span>NSInteger</span>)tableView:(<span>UITableView</span> *)tableView numberOfRowsInSection:(<span>NSInteger</span>)section {
<span><span>	</span></span>return<span> 20</span><span>; // every section has 5 rows
}</span></pre>
<pre>- (<span>UITableViewCell</span> *)tableView:(<span>UITableView</span> *)tableView cellForRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span><span>	</span></span><span>NSLog</span><span>(</span>@"cellForRowAtIndexPath called"<span>);
<span>	</span><span>static</span> <span>NSString</span> *CellIdentifier = <span>@"Cell"</span>;
<span>	</span><span>UITableViewCell</span> *cell = [tableView <span>dequeueReusableCellWithIdentifier</span>:CellIdentifier];
<span>	</span><span>if</span> (cell == <span>nil</span>) { NSLog(@"new cell");
<span><span>		</span>cell = [[[</span><span>UITableViewCell</span><span> </span>alloc<span>] </span>initWithFrame<span>:</span><span>CGRectZero</span><span> </span>reuseIdentifier<span>:CellIdentifier] </span>autorelease<span>];
<span>	</span>}
<span><span>	</span>cell.</span><span>text</span><span> = [NSString stringWithFormat</span>@"Cell #%i"indexPath.row]<span>;
<span>	</span><span>return</span> cell;
}</span></span></span></pre>
<p><img class="size-medium wp-image-790 alignleft" title="simplestableview" src="http://chris-software.com/wp-content/uploads/2009/05/simplestableview-161x300.png" alt="simplestableview" width="161" height="300" /></p>
<p style="text-align: left;">If you Build &amp; Go your project, you should get:</p>
<p>As you see <em>numberOfRowsInSection</em> method is quite obvious. In above example. I&#8217;m telling &#8211; preparing the <em>table</em> to display 8 rows in each section. As long as I didn&#8217;t tell the <em>table</em> how many sections there are in the table it <em>assumes</em> that I want to have 1 section. <em>cellForRowAtIndexPath</em> is &#8220;a little bit&#8221; more complex. Go to <em>Debugger Console</em> (<strong>Command+Shift+R</strong>) to open logs. Inside this method I added two functions to log whenever the method was called and whenever the <em>cell</em> is empty object (<em>nil</em>). To better understand this change the <em>numberOfRowsInSection</em> to return 20 for example, Build &amp; Go your project and study logs while scrolling the <em>UITableView</em>. <strong>Conclusion:</strong> because of memory management and overall performance <em>cellForRowAtIndexPath</em> is only called to show the visible <em>cells</em>, and when you scroll back to see the <em>cells</em> that have been already loaded, <em>cellForRowAtIndexPath</em> is called again, but it remembers their settings and customization and reuse them instead of allocating again. If you don&#8217;t understand this, treat it like a template you need to use in most <em>cellForRowAtIndexPath</em> method. <strong>indexPath</strong> gives you two information, what is the section of current cell (<em>indexPath.section</em>) and row (<em>indexPath.row</em>).</p>
<h3>Dynamic data source</h3>
<p><img class="alignleft size-medium wp-image-792" title="dynamicdatasimulator" src="http://chris-software.com/wp-content/uploads/2009/05/dynamicdatasimulator-161x300.png" alt="dynamicdatasimulator" width="161" height="300" />In this tutorial I will only show you simple examples of using <em>UITableView</em>, but you could prepare <em>NSMutableArray</em> to be displayed in <em>UITableView</em>. To do so, first add an <em>NSMutableArray</em> in header of your class:</p>
<pre><span>	</span><span>NSMutableArray</span> *dataForTable;</pre>
<p>and in <em>viewDidLoad</em> method:</p>
<pre>- (<span>void</span>)viewDidLoad {
<span><span>	</span></span><span>dataForTable</span><span> = [[</span><span>NSMutableArray</span><span> </span>alloc<span>] </span>initWithObjects<span>:
<span><span>					</span></span>@"First row"<span>,
<span><span>					</span></span>@"Second row"<span>,
<span><span>					</span></span>@"Third row"<span>,
<span>					</span><span>nil</span>];
<span><span>	</span>[</span>dataForTable<span> </span><span>retain</span><span>];
<span>	[</span><span>super</span><span> </span>viewDidLoad<span>];
}</span></span></span></span></span></span></pre>
<p>Now, <em>numberOfRowsInSection</em> shouldn&#8217;t return the static number 8, 20, or any other, but:</p>
<pre>- (<span>NSInteger</span>)tableView:(<span>UITableView</span> *)tableView numberOfRowsInSection:(<span>NSInteger</span>)section {
<span><span>	</span></span><span>return</span><span> [</span>dataForTable<span> </span><span>count</span><span>];
}</span></pre>
<p>And <em>cellForRowAtIndexPath</em> shouldn&#8217;t tell you what is the row&#8217;s number, but the object (<em>NSString</em>) from <em>NSMutableArray</em>.</p>
<pre><span>	</span>cell.<span>text</span> = [<span>dataForTable</span> <span>objectAtIndex</span>:indexPath.<span>row</span>];</pre>
<p><strong>Please note</strong>: once you changed the objects in <em>dataForTable</em> you can call <em>[myTable reloadData];</em> to redraw the table with new data.</p>
<h3>Table Styles</h3>
<div style="text-align: center;"><img class="alignnone size-medium wp-image-795" title="tablestyleplain" src="http://chris-software.com/wp-content/uploads/2009/05/tablestyleplain-206x299.png" alt="tablestyleplain" width="206" height="299" /><img class="alignnone size-medium wp-image-794" title="tablestylegrouped" src="http://chris-software.com/wp-content/uploads/2009/05/tablestylegrouped-206x299.png" alt="tablestylegrouped" width="206" height="299" /></div>
<div>There are two styles you can apply to <em>UITableView</em>. <strong>Plain</strong> (left, default) has &#8220;sticky headers&#8221;, <strong>Grouped</strong> (right) has rounded edges and stripped, gray background. Altough, so far there was no headers displayed by your code you can compare these two styles in <em>Phone</em> and <em>Settings</em><em> application</em>. You can switch the <em>style</em> in <em>Xcode</em>, but as long as you are using <em>Interface Builder</em>, simply go to <em>Table View Attributes</em> and change the S<em>tyle</em> property.</div>
<h3>Sections</h3>
<p>By default there is one section in every <em>UITableView</em>. If you want more &#8211; seperate one group of rows from the other, you have to implement the <em>numberOfSectionsInTableView</em> method:</p>
<pre>- (<span>NSInteger</span>)numberOfSectionsInTableView:(<span>UITableView</span> *)tableView {
    <span>return</span> 2;
}</pre>
<p>Above method will gave us one of these two results:</p>
<p style="text-align: center;"><img class="alignnone size-medium wp-image-797" title="sectionsplain" src="http://chris-software.com/wp-content/uploads/2009/05/sectionsplain-161x300.png" alt="sectionsplain" width="161" height="300" /> <img class="alignnone size-medium wp-image-796" title="sectionsgrouped" src="http://chris-software.com/wp-content/uploads/2009/05/sectionsgrouped-161x300.png" alt="sectionsgrouped" width="161" height="300" /></p>
<p>You should notice two things. In <em>grouped</em> style the space between sections is clearly visible, but not in <em>plain</em> style as long as you don&#8217;t provide <em>headers&#8217;</em> <em>names</em>. The second: both sections are identical, that&#8217;s because<em> numbersOfRowsInSection</em> is returning always the same value and the same is with <em>cellForRowAtIndexPath</em>. You can easily change it. You could do it dynamicaly, as shown before, but I will use <em>switch</em> instruction:</p>
<pre>- (<span>NSInteger</span>)tableView:(<span>UITableView</span> *)tableView numberOfRowsInSection:(<span>NSInteger</span>)section {
<span>	</span><span>switch</span> (section) {
<span>		</span><span>case</span> <span>0</span>:
<span><span>			</span></span>return<span> </span><span>5</span><span>;
<span><span>			</span></span>break<span>;
<span>		</span><span>case</span> <span>1</span>:
<span><span>			</span></span>return<span> </span><span>2</span><span>;
<span><span>			</span></span>break<span>;
<span>	</span>}
<span><span>	</span></span>return<span> </span><span>0</span><span>;
}</span></span></span></span></span></pre>
<p><img class="alignleft size-medium wp-image-798" title="customsections" src="http://chris-software.com/wp-content/uploads/2009/05/customsections-161x300.png" alt="customsections" width="161" height="300" />And (instead of <em>cell.text = [NSString ...</em>);</p>
<pre><span>	</span><span>switch</span> (indexPath.section) {
<span>		</span><span>case</span> <span>0</span>:
<span>			</span>cell.<span>text</span> = [<span>NSString</span> <span>stringWithFormat</span>:<span>@"Happy Cell #%i"</span>,indexPath.<span>row</span>];;
<span><span>			</span></span>break<span>;
<span>		</span><span>case</span> <span>1</span>:
<span>			</span>cell.<span>text</span> = [<span>NSString</span> <span>stringWithFormat</span>:<span>@"Sad Cell #%i"</span>,indexPath.<span>row</span>];;
<span><span>			</span></span>break<span>;
<span>	</span>}</span></span></pre>
<p>This code should be easily understandable for you. I've not done anything else but used <em>switch</em> instruction to <em>return / assign</em> different values for given cases. Since now, I'm going to skip <em>switch</em> instructions in sample codes, you should implement them on your own easily.</p>
<h3>Header and footer</h3>
<p style="text-align: center;"><img class="alignnone size-medium wp-image-799" title="headerfootergrouped" src="http://chris-software.com/wp-content/uploads/2009/05/headerfootergrouped-161x300.png" alt="headerfootergrouped" width="161" height="300" /> <img class="alignnone size-medium wp-image-800" title="headerfooterplain" src="http://chris-software.com/wp-content/uploads/2009/05/headerfooterplain-161x300.png" alt="headerfooterplain" width="161" height="300" /></p>
<p>As you see the <em>grouped UITableView</em> looks amazing with <em>headers</em> and <em>footers</em>, but for <em>plain</em> style, you should use only <em>headers</em> because it doesn't look good - <em>header</em> and <em>footer</em> look exactly the same. To achieve something like this you need to implement these two methods:</p>
<pre>-(<span>NSString</span> *)tableView:(<span>UITableView</span> *)tableView titleForHeaderInSection:(<span>NSInteger</span>)section {
<span><span>	</span></span><span>return</span><span> </span>@"Section title"<span>;
}</span></pre>
<pre>- (<span>NSString</span> *)tableView:(<span>UITableView</span> *)tableView titleForFooterInSection:(<span>NSInteger</span>)section {
<span><span>	</span></span><span>return</span><span> </span>@"Footer title"<span>;
}</span></pre>
<p><strong>Please note:</strong> if you return <em>nil</em> header / footer won't be displayed</p>
<h3>Section index</h3>
<p><img class="alignleft size-medium wp-image-801" title="tableindex" src="http://chris-software.com/wp-content/uploads/2009/05/tableindex-161x300.png" alt="tableindex" width="161" height="300" />When you scroll the contact list, the small letters <strong>A-Z</strong> on the right are very helpful, aren't thay? It's very easy to implement something like this.</p>
<pre>- (<span>NSArray</span> *)sectionIndexTitlesForTableView:(<span>UITableView</span> *)tableView {
<span><span>	</span></span>NSMutableArray<span> *index = [[</span>NSMutableArray<span> </span><span>alloc</span><span>] </span><span>initWithObjects</span><span>:</span><span>@"A"</span><span>,</span><span>@"B"</span><span>,</span><span>@"C"</span><span>,</span><span>@"D"</span><span>,</span><span>nil</span><span>];
<span>	</span><span>return</span> index;
}</span></pre>
<p>In <em>index</em> array you have to provide that titles that will be displayed on the whole height of <em>UITableView</em> on the right. The <em>titles</em> don't have to be the same as the headers' titles (but their should, or be similar). If you provide more <em>index titles</em> than there are <em>sections</em> in <em>UITableView</em>, most of them will navigate to the bottom section.</p>
<p><strong>Please note:</strong> <em>sectionIndexTitlesForTableView</em> should return a <em>NSArray</em> object, but you are returning <em>NSMutableArray</em>, don't worry, <em>NSMutableArray</em> is just a subclass of <em>NSArray</em> so this is acceptable and doesnn't cause any logical errors.</p>
<p><strong>Please note:</strong> section index works only in <em>plain</em> style of <em>UITableView</em>.</p>
<h3>Pressing the cell</h3>
<p><img class="alignleft size-medium wp-image-802" title="cellpressed" src="http://chris-software.com/wp-content/uploads/2009/05/cellpressed-161x300.png" alt="cellpressed" width="161" height="300" />The cell usually links to some actions. Here is the sample action to displays an <em>alert</em> with information what <em>cell</em> was selected.</p>
<pre>- (<span>void</span>)tableView:(<span>UITableView</span> *)tableView didSelectRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span><span>	</span></span><span>UIAlertView</span><span> *alert = [[</span><span>UIAlertView</span><span> </span>alloc<span>] </span>initWithTitle<span>:</span><span>@"Cell pressed"</span><span> </span>message<span>:[</span><span>NSString</span><span> </span>stringWithFormat<span>:</span><span>@"Cell #%i in section #%i"</span><span>,indexPath.row,indexPath.</span>section<span>] </span>delegate<span>:</span><span>self</span><span> </span>cancelButtonTitle<span>:</span><span>@"OK"</span><span> </span>otherButtonTitles<span>:</span><span>nil</span><span>];
<span>	</span>[alert <span>show</span>];
<span>	</span>[alert <span>release</span>];
}</span></pre>
<p>And there is one "visual thing" you could add to maintain the nice aesthetics. Once <em>cell</em> (<em>UITableViewCell</em>)<em> </em>was pressed it stays selected - highlighted until you press any other cell or scroll the <em>UITableView</em>. Just add this line of code to above method to fix it:</p>
<pre><span><span>	</span>[tableView </span>deselectRowAtIndexPath<span>:indexPath </span>animated<span>:</span><span>YES</span><span>];</span></pre>
<h3>Accessory Buttons</h3>
<p><em><img class="alignleft size-full wp-image-803" style="margin: 5px;" title="accessorybuttons" src="http://chris-software.com/wp-content/uploads/2009/05/accessorybuttons.png" alt="accessorybuttons" width="192" height="130" />Accessory Buttons </em>are this nice tiny usually arrow-images on the right side of <em>UITableViewCell</em> with custom actions once tapped (only #2). There are 3 types of <em>accessory buttons</em>:</p>
<p>1. <em>UITableViewCellAccessoryCheckmark</em><br />
2. <em>UITableViewCellAccessoryDetailDisclosureButton</em><br />
3. <em>UITableViewCellAccessoryDisclosureIndicator</em></p>
<pre>- (<span>UITableViewCellAccessoryType</span>)tableView:(<span>UITableView</span> *)tableView accessoryTypeForRowWithIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span><span>	</span></span><span>return</span><span> </span>UITableViewCellAccessoryCheckmark<span>;</span>

<span>}</span></pre>
<p>If you don't want to display any <em>accessory button</em> for some <em>cells</em> simply return <em>UITableViewCellAccessoryNone</em> for them. If you used <em>DetailDisclosureButton</em> (nice blue button with arrow) you can perform some tasks, once it was tapped:</p>
<pre>- (<span>void</span>)tableView:(<span>UITableView</span> *)tableView accessoryButtonTappedForRowWithIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span><span>	</span></span><span>UIAlertView</span><span> *alert = [[</span><span>UIAlertView</span><span> </span>alloc<span>] </span>initWithTitle<span>:</span><span>@"Accessory Button pressed"</span><span> </span>message<span>:[</span><span>NSString</span><span> </span>stringWithFormat<span>:</span><span>@"Accessory Button for Cell #%i in section #%i"</span><span>,indexPath.row,indexPath.</span>section<span>] </span>delegate<span>:</span><span>self</span><span> </span>cancelButtonTitle<span>:</span><span>@"OK"</span><span> </span>otherButtonTitles<span>:</span><span>nil</span><span>];
<span>	</span>[alert <span>show</span>];
<span>	</span>[alert <span>release</span>];
}</span></pre>
<p><strong>Please note</strong>: above method works only with <em>UITableViewCellAccessoryDetailDisclosureButton</em> and it doesn't call any method connected with selecting a row.</p>
<h2>Height and indent</h2>
<p style="text-align: center;"><img class="alignnone size-medium wp-image-806" title="sizeplain" src="http://chris-software.com/wp-content/uploads/2009/05/sizeplain-161x300.png" alt="sizeplain" width="161" height="300" /> <img class="alignnone size-medium wp-image-805" title="sizegrouped" src="http://chris-software.com/wp-content/uploads/2009/05/sizegrouped-161x300.png" alt="sizegrouped" width="161" height="300" /></p>
<p style="text-align: left;">If needed you can change the <em>height</em> of any cell or it's <em>indend</em> as shown screenshots above. By default <em>height=45</em> and <em>indent=0</em>.</p>
<pre>- (<span>CGFloat</span>)tableView:(<span>UITableView</span> *)tableView heightForRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span>	</span><span>if</span> (indexPath.row == <span>2</span>) <span>return</span> <span>90</span>;
<span><span>	</span></span>return<span> </span><span>45</span><span>;
}
- (<span>NSInteger</span>)tableView:(<span>UITableView</span> *)tableView indentationLevelForRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span>	</span><span>if</span> (indexPath.row == <span>3</span>) <span>return</span> <span>2</span>;
<span><span>	</span></span>return<span> </span><span>0</span><span>;
}</span></span></pre>
<h3>Custom Cell</h3>
<p><img class="alignleft size-medium wp-image-807" title="customcellib" src="http://chris-software.com/wp-content/uploads/2009/05/customcellib-199x300.png" alt="customcellib" width="199" height="300" />As you see there are many possibilities of customizing the cell, but it's not enough. You can create a new <strong>.xib</strong> file and a <em>UITableViewCell</em> controller and design the <em>cell</em> like any <em>view</em> so far.</p>
<p>In <em>Xcode </em>add new class of type <em>UITableViewCell</em> and <em>View XIB</em> (name them <strong>CustomCell.*</strong>).</p>
<p>In <strong>CustomCell.h</strong> any any <em>IBOutlets</em> you need, labels, slider, switches... whatever.</p>
<p>Open <strong>CustomCell.xib</strong> and delete the <em>View</em> and add add <em>UITableViewCell</em> to <strong>CustomCell.xib</strong>. In <em>Table View Cell Identity</em> set class = <em>CustomCell</em> (not <strong>File's Owner</strong> this time). If you want you can adjust the size in <em>Custom Cell Size...</em></p>
<p style="text-align: center;"><em><img class="size-medium wp-image-808 alignnone" title="customcellsize" src="http://chris-software.com/wp-content/uploads/2009/05/customcellsize-171x300.png" alt="customcellsize" width="171" height="300" /></em></p>
<p style="text-align: left;">or by dragging the bottom right triangle. Set it's features in <em>Custom Cell Attributes</em>, add some objects - treat it like a typical <em>UIView.</em></p>
<p style="text-align: left;"><em>Please note:</em> this time, <em>UITableViewCustomCell</em> is a class of <em>CustomCell</em>, not <em>File's Owner</em> as usuall. So when you want to make connections go to <em>Custom Cell Connections</em>, forget about <strong>File's Owner</strong> this time.</p>
<p style="text-align: left;">OK, your custom cell is prepared right now, now it's time to show it in the <em>UITableView</em>. First you need to import <strong>CustomCell.h</strong> to your class that manages <em>table</em> (<em>#import "CustomCell.h"</em> and <em>@class CustomCell</em>).</p>
<p style="text-align: left;">Now you have to reorganize the <em>table</em>. Let's assume that your custom cell will be displayed only once in seperated section - in <em>numberOfSectionsInTableView</em> tell that there will be one more section and in <em>numbersOfRowsInSection</em> return <em>1</em> for a given section (add next <em>case</em> for existing <em>switch</em>).</p>
<p style="text-align: left;">Hope above wasn't difficult because this will be: now it's time to extend <em>cellForRowAtIndexPath</em> method. I'm like many times before using switch and I assume that <em>custom cell</em> will be displayed in 4th section:</p>
<pre>- (<span>UITableViewCell</span> *)tableView:(<span>UITableView</span> *)tableView cellForRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span><span>	</span></span>// custom cell only
<span>	</span><span>if</span> (indexPath.section == <span>3</span>) {
<span>		</span><span>static</span> <span>NSString</span> *CellIdentifier = <span>@"CustomCell"</span>;
<span>		</span><span>CustomCell</span> *cell = (<span>CustomCell</span> *) [tableView <span>dequeueReusableCellWithIdentifier</span>:CellIdentifier];
<span>		</span><span>if</span> (cell == <span>nil</span>) {
<span><span>			</span></span><span>NSArray</span><span> *outlets = [[</span><span>NSBundle</span><span> </span>mainBundle<span>] </span>loadNibNamed<span>:</span><span>@"CustomCell"</span><span> </span>owner<span>:</span><span>self</span><span> </span>options<span>:</span><span>nil</span><span>];
<span>			</span><span>for</span> (<span>id</span> currentObject <span>in</span> outlets) {
<span>				</span><span>if</span> ([currentObject <span>isKindOfClass</span>:[<span>UITableViewCell</span> <span>class</span>]]){
<span>					</span>cell =  (<span>CustomCell</span> *) currentObject;
<span>					</span><span>break</span>;
<span>				</span>}
<span>			</span>}
<span>		</span>}
<span><span>		</span>cell.</span><span>myLabel.text</span><span> = </span>@"Some text"<span>;
<span>		</span><span>return</span> cell;
<span>	</span>}</span></span>

	// other cells:
	// ...</pre>
<p>So, when it comes to 4th section (<em>indexPath.section == 3</em>), the <strong>CustomCell</strong> nib (<strong>.xib</strong>) file is loaded, and in <em>for</em> loop, all it's objects are assigned as properties to <em>cell</em>. Although you set the size of <em>custom cell</em> in <em>Interface Builder,</em> but you must also tell <em>UITableView</em> to expect this by extending <em>heightForRowAtIndexPath</em> method:</p>
<pre>- (<span>CGFloat</span>)tableView:(<span>UITableView</span> *)tableView heightForRowAtIndexPath:(<span>NSIndexPath</span> *)indexPath {
<span>	</span><span>if</span> (indexPath.row == <span>2</span>) <span>return</span> <span>90</span>;
<span>	</span><span><strong>else</strong></span><strong> </strong><span><strong>if</strong></span><strong> (indexPath.section == </strong><span><strong>3</strong></span><strong>) </strong><span><strong>return</strong></span><strong> </strong><span><strong>95</strong></span><strong>;</strong>
<span><span>	</span></span>return<span> </span><span>45</span><span>;
}</span></pre>
<p style="text-align: center;"><img class="size-full wp-image-809 aligncenter" title="customcellsimulator" src="http://chris-software.com/wp-content/uploads/2009/05/customcellsimulator.png" alt="customcellsimulator" width="320" height="145" /></p>
<h3><strong>Please note:</strong></h3>
<p style="text-align: left;">you can read more about <em>UITableView</em> in documentation: check descriptions of <em>UITableViewDelegate</em> and <em>UITableViewDataSource</em> protocols. You will find there more options and methods allowing you to modify the <em>UITableView</em> - delete, add, edit, reorder rows and more.</p>
<p style="text-align: left;">
<h3>Conclusion:</h3>
<p>That was pretty much for the one tutorial. Hope you understand everything. Don't worry, <em>tables</em> are something that young developers try to avoid, but they are not so difficult at all. I provided for you a sample project. Remember to change occasionally in <em>Interface Builder</em> the style of <em>UITableView</em> (<em>plain / grouped</em>). Some methods are disabled by comments, you can enable them by yourself.</p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/tableview.zip"><img class="alignnone size-full wp-image-564" title="xcodeproj" src="http://chris-software.com/wp-content/uploads/2009/04/xcodeproj.png" alt="xcodeproj" width="128" height="128" /></a></p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/tableview.zip">Download the project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/05/tables/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Instruments</title>
		<link>http://chris-software.com/index.php/2009/05/05/instruments/</link>
		<comments>http://chris-software.com/index.php/2009/05/05/instruments/#comments</comments>
		<pubDate>Tue, 05 May 2009 14:56:21 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[SDK Tools]]></category>
		<category><![CDATA[Instruments]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=776</guid>
		<description><![CDATA[
Instruments is the great tool to measure the performance of your application, problems, object allocations, memory leaks and more.
I personally don&#8217;t use it quite often. Why? I don&#8217;t have problems with memory leaks, because I know where I have to release some objects, where to keep them. How about performance? I measure the performance by [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://chris-software.com/wp-content/uploads/2009/05/instrumentsscreenshot.png"><img class="alignnone size-full wp-image-777" title="instrumentsscreenshot" src="http://chris-software.com/wp-content/uploads/2009/05/instrumentsscreenshot.png" alt="instrumentsscreenshot" width="648" height="472" /></a></p>
<p><a href="http://chris-software.com/wp-content/uploads/2009/04/dev_instrumentsmedium.png"><img class="alignleft size-full wp-image-449" style="margin-left: 5px; margin-right: 5px;" title="dev_instrumentsmedium" src="http://chris-software.com/wp-content/uploads/2009/04/dev_instrumentsmedium.png" alt="dev_instrumentsmedium" width="256" height="256" /></a><em>Instruments</em> is the great tool to measure the performance of your application, problems, object allocations, memory leaks and more.</p>
<p>I personally don&#8217;t use it quite often. Why? I don&#8217;t have problems with <em>memory leaks</em>, because I know where I have to <em>release</em> some objects, where to keep them. How about performance? I measure the performance by debugging my application on the real device. Please remember, that iPod touch 2nd gen offers better performance because of it&#8217;s faster CPU. If your app runs smoothly on iPhone it will run even better on iPod touch but not vice versa!</p>
<p>OK, so far I told you my atitude to <em>Instruments</em>, but I&#8217;ve never said that I don&#8217;t use this tool at all. Of course I use. The goal of your application/game should&#8217;t be only the metter of how much fun or usability it provides, but also how long it takes to load, during gameplay not to show <em>Loading screen</em> every minute, uses as much memory as possible and cleans after app terminates.</p>
<p>Using the information from <em>Instruments</em> you have the great opportunity to improve your application. Use your application and track the graphs <em>Instruments</em> provides, optimize methods and delete any objects that has been allocated, but no longer needed.</p>
<p>In fact it&#8217;s difficult to describe, how you should use <em>Instruments</em>. The results are different for each application and differently interpreted by each developer. It&#8217;s up to you how <em>Instruments</em> can help you in development. If you can&#8217;t self-learn how to use this tool, I recommand you to read <em>Instruments&#8217; help</em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/05/instruments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Short sounds</title>
		<link>http://chris-software.com/index.php/2009/05/05/short-sounds/</link>
		<comments>http://chris-software.com/index.php/2009/05/05/short-sounds/#comments</comments>
		<pubDate>Tue, 05 May 2009 14:13:07 +0000</pubDate>
		<dc:creator>Chris</dc:creator>
				<category><![CDATA[Obj-C Tutorials]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[music]]></category>
		<category><![CDATA[play]]></category>
		<category><![CDATA[Short sounds]]></category>

		<guid isPermaLink="false">http://chris-software.com/?page_id=767</guid>
		<description><![CDATA[Related tutorials:

Playing background music

Sounds are very important to put some life into your application, usually the game.
What is the difference between short sounds and long sounds? Let&#8217;s say, you are making a game and there is a constantly looping (or changing the track once played) background music. This is certainly not a short sound and [...]]]></description>
			<content:encoded><![CDATA[<h3>Related tutorials:</h3>
<ul>
<li><span style="color: #551a8b; text-decoration: underline;"><a href="http://chris-software.com/index.php/2009/05/09/playing-backgroud-music/">Playing background music</a></span></li>
</ul>
<p>Sounds are very important to put some life into your application, usually the game.</p>
<p>What is the difference between short sounds and long sounds? Let&#8217;s say, you are making a game and there is a constantly looping (or changing the track once played) background music. This is certainly not a short sound and it will be discuss somewhere else. You can play a short sound once you press the button, hit the wall, an alert occurred, a weapon was used&#8230; This kind of sounds could also be played as a background music but there is one problem with playing few background musics on iPhone&#8230; The iPhone processor can deal only with one background music and many sounds, that&#8217;s why music played from your library on iPhone / iPod touch stops once any app starts to play background music.</p>
<p>Sounds cannot be longer the 30 seconds and you should convert them before adding to the project. How? Open <strong>Terminal</strong> application on your mac and use the <strong>afconvert</strong>:</p>
<pre>/usr/bin/afconvert -f caff -d LEI16 input_file output_file</pre>
<p>Example:</p>
<pre>MBP-Krzysiek:~ Krzysiek$ /usr/bin/afconvert -f caff -d LEI16 /Users/Krzysiek/Desktop/samlpe\ music.mp3 /Users/Krzysiek/Desktop/samplemusic.caf</pre>
<div style="text-align: center; "><a href="http://chris-software.com/wp-content/uploads/2009/05/terminal.png"><img class="alignnone size-full wp-image-768" title="terminal" src="http://chris-software.com/wp-content/uploads/2009/05/terminal.png" alt="terminal" width="585" height="447" /></a></div>
<div style="text-align: left; ">Please bear in mind that <strong>.caf</strong> aren&#8217;t like <strong>.mp3</strong> &#8211; the lossless format, that&#8217;s why after conversion the sound file is usually bigger than original. That&#8217;s why you shouldn&#8217;t have original files in <strong>.mp3</strong> as shown on example, but even you have <strong>.caf</strong>, convert it anyway. <em>afconvert</em> converts almost any sound format I know (but I don&#8217;t know many, I&#8217;m not DJ).</div>
<div style="text-align: left; ">OK, your sound is ready to add to your project. Now in <em>Xcode</em> you need to write a class responsible for playing a sound. I will show you two ways: playing a sounds using:</div>
<div style="text-align: left; ">
<ul>
<li><em>SystemSound</em></li>
<li><em>AVAudioPlayer</em></li>
</ul>
</div>
<h2>SystemSound</h2>
<p><em>SystemSound</em> plays any sound without affecting the background music of your application or music from <em>iPod</em>. It doesn&#8217;t provide any volume control, user can control volume by changing the master volume of the device. Before you start to code, you need to add an <strong>AudioToolbox</strong> framework to your project (if you don&#8217;t know how: ctrl-press any existing <strong>.framework</strong>, <em>Reveal in Finder</em> and drag and drop the <strong>AudioToolbox.framework</strong> to the <em>Frameworks group</em>).</p>
<p>Add a new class (name it <strong>sounds</strong>) to your project, choose <strong>NSObject subclass</strong>, but in fact, it doesn&#8217;t metter, if you replace all code in <em>header</em> and <em>implementation</em> file with these provided by me:</p>
<p><strong>sounds.h</strong></p>
<pre><span>#import </span>&lt;Foundation/Foundation.h&gt;
<span>#import </span>&lt;AudioToolbox/AudioServices.h&gt;

<span>@interface</span> sounds : NSObject {
<span><span>	</span></span>SystemSoundID<span> </span><span>soundID</span><span>;
}
-(<span>id</span>) initWithContentsOfFile:(<span>NSString</span> *)path;
-(<span>void</span>)play;
@end</span></pre>
<p><strong>sounds.m</strong></p>
<pre><span>#import </span>"sounds.h"

@implementation<span> sounds
-(<span>id</span>) initWithContentsOfFile:(<span>NSString</span> *)path {
<span><span>	</span></span>self<span> = [</span>super<span> </span><span>init</span><span>];
<span>	</span><span>if</span> (<span>self</span> != <span>nil</span>) {
<span>		</span><span>NSURL</span> *filePath = [<span>NSURL</span> <span>fileURLWithPath</span>:path <span>isDirectory</span>:<span>NO</span>];
<span><span>		</span></span>AudioServicesCreateSystemSoundID<span>((</span><span>CFURLRef</span><span>)filePath, &amp;</span><span>soundID</span><span>);
<span>	</span>}
<span><span>	</span></span>return<span> </span>self<span>;
}
-(<span>void</span>)play {
<span><span>	</span></span>AudioServicesPlaySystemSound<span>(</span><span>soundID</span><span>);
}
-(<span>void</span>)dealloc {
<span><span>	</span></span>AudioServicesDisposeSystemSoundID<span>(</span><span>soundID</span><span>);
<span><span>	</span>[</span><span>super</span><span> </span>dealloc<span>];
}
@end</span></span></span></span></span></span></span></pre>
<p>Import <strong>sounds.h</strong> (<em>#import &#8220;sounds.h&#8221;</em>) to any class (for example <strong>game.h</strong>) that will call <em>sounds</em> class to play a short sound. If the sound is played many times (like in most cases) add in header the object:</p>
<pre><span><span>	</span>sounds</span><span> *myS</span>ound<span>;</span></pre>
<p>or</p>
<pre><span><span>	</span>sounds</span><span> *myS</span>ound1, *mySound2, *mySound3<span>; // , *mySound4 ... *mySound(n)</span></pre>
<p>or</p>
<pre><span><span>	</span>sounds</span><span> *myS</span>ound[3];</pre>
<div>Before any sound can be played you need to allocate it. While allocating you have to call the method <em>initWithContentsOfFile</em> and provide the <em>path</em> to the resource &#8211; sound file.</div>
<pre><span><span>	</span>mySound</span><span> = [[sounds</span><span> </span>alloc<span>] </span>initWithContentsOfFile<span>:[[</span><span>NSBundle</span><span> </span>mainBundle<span>] </span>pathForResource<span>:</span><span>@"<strong>myFunnySound</strong>"</span><span> </span>ofType<span>:</span><span>@"<strong>caf</strong>"</span><span>]];</span></pre>
<div>Now <em>mySound</em> object is ready to play <strong>myFunnySound.caf</strong>.</div>
<div>To play call the <em>play</em> method: <em>[mySound play];</em>. That&#8217;s all about <em>SystemSounds</em>.</div>
<div><strong>Please note:<br />
<em>System Sounds</em><em> can also toggle vibration, but it will be discussed in other tutorial.</em> </strong></div>
<h2>AVAudioPlayer</h2>
<p><em>AvAudioPlayer</em> plays any sound also without affecting the background music of your application, but it terminates the music from iPod. It gives the user the ability to control the volume within the application (if you provide a <em>slider</em> or any other interface to adjust the volume), or by changing the master volume of the device. Before you can use <em>AVAudioPlayer</em> you need to add <strong>AVFoundation.framework</strong> to your project.</p>
<p><strong>Please note:<br />
<span style="font-weight: normal;">Using <em>AVAudioPlayer</em> is much simpler than <em>SystemSounds</em>. I implemented a class to use <em>SystemSounds</em>, because I don&#8217;t like using such a long method names (<em>AudioServicesPlaySystemSound</em>) when they are called frequently. To play sound with <em>AVAudioPlayer</em> I need only 2-3 lines of code so writing a class to handle it is pointless and useless for me.</span></strong></p>
<p>To prepare the sound you need to repeat almost the same steps I told in <em>SystemSounds</em>. Let&#8217;s add in the <em>header</em> file of your class an instruction to import <em>AVAudioPlayer.h</em> framework:</p>
<pre><span>#import </span>&lt;AVFoundation/AVAudioPlayer.h&gt;</pre>
<p>And the <em>AVAudioPlayer</em> object with our sound:</p>
<pre><span><span>	</span></span>AVAudioPlayer<span> *myAVsound</span><span>;</span></pre>
<p>To start, and assing the sound file you also need to provide a path to that resource:</p>
<pre><span><span>	</span>my</span><span>AVsound</span><span> = [[</span><span>AVAudioPlayer</span><span> </span>alloc<span>] </span>initWithContentsOfURL<span>:[</span><span>NSURL</span><span> </span>fileURLWithPath<span>:[[</span><span>NSBundle</span><span> </span>mainBundle<span>] </span>pathForResource<span>:</span><span>@"<strong>myFunnySound</strong>"</span><span> </span>ofType<span>:</span><span>@"<strong>caf</strong>"</span><span>]  ] </span>error<span>:</span><span>NULL</span><span>];</span></pre>
<p>The method to play this sound couldn&#8217;t be simpler:</p>
<pre><span><span>	</span>[</span><span>myAVsound play]</span><span>;</span></pre>
<p>&#8230; and to adjust the volume:</p>
<pre><span><span>	</span>myAVsound.volume = 0.6</span><span>;</span></pre>
<p>The volume can be adjusted also during the sound is being played.</p>
<p><strong>Please note:<br />
<span style="font-weight: normal;">The given volume should be a number from range </span>&lt;0.0,1.0&gt;</strong>. When the <em>volume=0</em>, user won&#8217;t hear the sound at all (<em>O RLY?</em>). You could also set the <em>volume=2.0</em> or <em>10.0</em> but <strong>be careful<span style="font-weight: normal;">.</span></strong> Instead of the louder sound you can get an unbearable to here noise (especially when the sound is saved in low quality), it can be harmful to user&#8217;s ear, if he uses headset, or can damage the device&#8217;s speaker.</p>
<p><strong>BTW:<br />
<em>AVAudioPlayer</em><em> allows you to loop the sound (<em>myAVsound.numberOfLoops = 2;</em>).</em> </strong></p>
<h3><strong>Please note:</strong></h3>
<p>I&#8217;ve heard many problems with playing the sounds with <em>iPhone Simulator</em>, in other words, the project cannot be compiled to run on <em>iPhone Simulator</em>. I personally have this problem, but as long as I participate in iPhone Developer program. I guess (but I&#8217;m not sure) that is because of computer you use. I use <em>MacBook Pro Mid/Late 2007 (MA895) 2.2 GHz</em>. As long as I know, this problem doesn&#8217;t occur on MacBook Pros shipped with unibody enclosure.</p>
<p>That&#8217;s almost everything you need to know about short sounds. You can download the sample project below.It allows you to play a sound (included in the project) via <em>SystemSound</em> and via <em>AVAudio Player</em> with slider adjusting the volume.</p>
<p style="text-align: center;"><img class="size-medium wp-image-769 aligncenter" style="border: 1px solid black;" title="screenshotsounds" src="http://chris-software.com/wp-content/uploads/2009/05/screenshotsounds-200x300.png" alt="screenshotsounds" width="200" height="300" /></p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/soundengine.zip"><img class="alignnone size-full wp-image-564" title="xcodeproj" src="http://chris-software.com/wp-content/uploads/2009/04/xcodeproj.png" alt="xcodeproj" width="128" height="128" /></a></p>
<p style="text-align: center;"><a href="http://chris-software.com/wp-content/uploads/2009/05/soundengine.zip">Download the project</a></p>
]]></content:encoded>
			<wfw:commentRss>http://chris-software.com/index.php/2009/05/05/short-sounds/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
	</channel>
</rss>

