<?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>ObjColumnist &#187; Cocoa</title>
	<atom:link href="http://objcolumnist.com/category/cocoa/feed/" rel="self" type="application/rss+xml" />
	<link>http://objcolumnist.com</link>
	<description>Coding under the Hammer</description>
	<lastBuildDate>Sun, 11 Jul 2010 11:54:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=abc</generator>
		<item>
		<title>URL Encoding</title>
		<link>http://objcolumnist.com/2009/10/25/escaping-a-url/</link>
		<comments>http://objcolumnist.com/2009/10/25/escaping-a-url/#comments</comments>
		<pubDate>Sun, 25 Oct 2009 14:27:49 +0000</pubDate>
		<dc:creator>Spencer MacDonald</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[iPhone]]></category>

		<guid isPermaLink="false">http://objcolumnist.com/?p=137</guid>
		<description><![CDATA[If you have tried to send any information using a GET web request, you would have come across an annoying problem. That annoying problem is making sure that the URL is correctly encoded. At first glance it would seem that the Cocoa Frameworks do this for you, and you would be right &#8230;. well kind [...]]]></description>
			<content:encoded><![CDATA[<p>If you have tried to send any information using a GET web request, you would have come across an annoying problem. That annoying problem is making sure that the URL is correctly encoded.</p>
<p>At first glance it would seem that the Cocoa Frameworks do this for you, and you would be right &#8230;. well kind of.</p>
<p>The issue is that by default most of these methods leave characters such as &#038; = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request in valid.</p>
<p>Luckily there is a function in Core Foundation that helps:<br />
<code><br />
CFStringRef CFURLCreateStringByAddingPercentEscapes (<br />
   CFAllocatorRef allocator,<br />
   CFStringRef originalString,<br />
   CFStringRef charactersToLeaveUnescaped,<br />
   CFStringRef legalURLCharactersToBeEscaped,<br />
   CFStringEncoding encoding<br />
);<br />
</code></p>
<p>What makes this function useful, is the <strong>legalURLCharactersToBeEscaped</strong> parameter. This will escape legal characters such as &#038; ? = if they are supplied. This allows you to escape parameters using the following code.<br />
<code></p>
<p>CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)parameter, NULL, CFSTR(":/?#[]@!$&#038;’()*+,;="), kCFStringEncodingUTF8)<br />
</code></p>
<p>An example of when to use this, is Twitters Update status API. You can find that here http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update</p>
<p>To update your status to the following:</p>
<p><strong>This is my status</strong></p>
<p>You would need to post up the following URL:</p>
<p>http://twitter.com/statuses/update.xml?status=This%20is%20my%20status</p>
<p>As this is such a common problem of mine, I have created a category on NSURL. This allows you to pass in a base URL and a parameters dictionary.</p>
<p><code></p>
<p>+ (NSURL *)URLWithBaseString:(NSString *)baseString parameters:(NSDictionary *)parameters{</p>
<p>	NSMutableString *urlString =[NSMutableString string];</p>
<p>	//The URL starts with the base string<br />
	[urlString appendString:baseString];</p>
<p>	NSString *escapedString;</p>
<p>	NSInteger keyIndex = 0;</p>
<p>	for (id key in parameters) {</p>
<p>		//First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an &#038;<br />
		if(keyIndex ==0)<br />
		{<br />
			escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&#038;’()*+,;="), kCFStringEncodingUTF8);<br />
			[urlString appendFormat:@"?%@=%@",key,escapedString];<br />
			[escapedString release];<br />
		}else{</p>
<p>			escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&#038;’()*+,;="), kCFStringEncodingUTF8);<br />
			[urlString appendFormat:@"&#038;%@=%@",key,escapedString];<br />
			[escapedString release];</p>
<p>		}</p>
<p>		keyIndex++;<br />
	}</p>
<p>	return [NSURL URLWithString:urlString];</p>
<p>}</p>
<p></code></p>
<p>Using a parameters dictionary keeps the code nice and clean, but beware, to use the category method above you still have to make sure that your keys, and the base URL are correctly encoded (no spaces or invalid characters !!!!!).</p>
<p>As we now have a category method to do all the hard work for us, to create the Twitter URL you just need to do the following:<br />
<code><br />
        NSString *baseString=@"http://twitter.com/statuses/update.xml";<br />
	NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"This is my status",@"status",nil];<br />
	NSURL *url=[NSURL URLWithBaseString:baseString parameters:dictionary];<br />
</code></p>
<p>And thats it. Obviously this category can be used for things other than twitter &#8230;.. if you really want to.</p>
]]></content:encoded>
			<wfw:commentRss>http://objcolumnist.com/2009/10/25/escaping-a-url/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Reopening an application&#8217;s main window by clicking on the Dock Icon</title>
		<link>http://objcolumnist.com/2009/08/09/reopening-an-applications-main-window-by-clicking-the-dock-icon/</link>
		<comments>http://objcolumnist.com/2009/08/09/reopening-an-applications-main-window-by-clicking-the-dock-icon/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 10:57:29 +0000</pubDate>
		<dc:creator>Spencer MacDonald</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[Mac]]></category>
		<category><![CDATA[Objective-C]]></category>
		<category><![CDATA[Quick Tip]]></category>

		<guid isPermaLink="false">http://objcolumnist.com/?p=128</guid>
		<description><![CDATA[When building Mac applications, Apple usually takes care of most of the default behaviours for you. One thing that Mac applications don&#8217;t do by default is, reopening the applications main window (if it has been closed), when the dock icon is pressed. Although this information is very hard to find in the documentation, but is [...]]]></description>
			<content:encoded><![CDATA[<p>When building Mac applications, Apple usually takes care of most of the default behaviours for you. One thing that Mac applications don&#8217;t do by default is, reopening the applications main window (if it has been closed), when the dock icon is pressed.</p>
<p>Although this information is very hard to find in the documentation, but is actually very easy to. The method you need to find is:</p>
<p><code><br />
- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag;<br />
</code></p>
<p>This is an optional delegate method that your AppDelegate can choose to implement, and is called when the user presses your application&#8217;s dock icon. The bool flags indicates whether the application has any visible windows. To reopen your application&#8217;s main window, you need to have a pointer to it (In the example below assume that it is defined as NSWindow *window; in the header file). If you do have a pointer to then you simple need to implement the code below.<br />
<code></p>
<p>- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag{</p>
<p>	if(flag==NO){<br />
		[window makeKeyAndOrderFront:self];<br />
	}<br />
	return YES;<br />
}</code></p>
<p>It is as simple as that.</p>
]]></content:encoded>
			<wfw:commentRss>http://objcolumnist.com/2009/08/09/reopening-an-applications-main-window-by-clicking-the-dock-icon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NSUserDefaults (Preferences)</title>
		<link>http://objcolumnist.com/2009/06/28/nsuserdefaults-preferences/</link>
		<comments>http://objcolumnist.com/2009/06/28/nsuserdefaults-preferences/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 11:57:44 +0000</pubDate>
		<dc:creator>Spencer MacDonald</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[CocoaTouch]]></category>

		<guid isPermaLink="false">http://objcolumnist.com/?p=89</guid>
		<description><![CDATA[Not everybody likes their applications to behave in the same way, and this is why the majority of Mac and iPhone applications have preferences. The default way to handle these preferences is using the class NSUserDefaults. NSUserDefaults are stored on the file system as .plist, which is simply an XML document. The way you access [...]]]></description>
			<content:encoded><![CDATA[<p>Not everybody likes their applications to behave in the same way, and this is why the majority of Mac and iPhone applications have preferences. The default way to handle these preferences is using the class NSUserDefaults.</p>
<p>NSUserDefaults are stored on the file system as .plist, which is simply an XML document. The way you access NSUserDefaults programatically is very much like accessing an NSMutableDictionary, that is by using keys.</p>
<p><strong>Setting User Defaults</strong></p>
<p>NSUserDefaults can be a bool, float, integer or an object. So if you wanted to set the autosave option (which is a BOOL) for your application to be YES, you would write:<br />
<code><br />
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"AutoSave"];<br />
</code></p>
<p>Moreover if you wanted to set the person&#8217;s name to ObjColumnist you would write:<br />
<code></p>
<p>[[NSUserDefaults standardUserDefaults] setObject:@"ObjColumnist" forKey:@"PersonName"];<br />
</code></p>
<p><strong>Reading User Defaults</strong></p>
<p>Reading the user defaults is just as easy as setting them. If we wanted to retrieve the 2 values we stored above, you would simply write:<br />
<code></p>
<p>NSString *name = [ [NSUserDefaults standardUserDefaults] stringForKey:@"PersonName"];<br />
BOOL autoSave =  [ [NSUserDefaults standardUserDefaults] boolForKey:@"AutoSave"];<br />
</code></p>
<p>You should also notice that there is a convenience method for retrieving a string for a key, even though we set it as an object.</p>
<p>It is also important to be aware that if you attempt to retrieve a numeric value such as an integer, <em>integerForKey:</em> for a non existent key, you will get the value 0. This is obviously an issue if 0 would trigger a certain preference in you application.</p>
<p><strong>Setting the default user defaults</strong></p>
<p>So you can now set and read the user defaults, but how do you assign their default values ?</p>
<p>The answer is <strong>registerDefaults:</strong></p>
<p>This method is usually called in the initialize (class) method of a given application&#8217;s AppController. The parameter for this method is an NSDictionary. The code below sets the default preference for the AutoSave option to YES, and the person&#8217;s name to @&#8221;unknown&#8221;.<br />
<code></p>
<p>NSMutableDictionary *defaults=[NSMutableDictionary dictionary];</p>
<p>[defaults setObject:[NSNumber numberWithBool:YES] forKey:@"AutoSave"];<br />
[defaults setObject:@"unknown" forKey:@"PersonName"];</p>
<p>[[NSUserDefaults standardUserDefaults] registerDefaults: defaults];</p>
<p></code></p>
<p>One thing that Cocoa does for you automatically without needing any extra code, is that it only saves to the .plist the values that are different to the defaults values, that were registered using <strong>registerDefaults:</strong> . This means that if the user does not change any of their default preference settings, there will no be a preference file created.</p>
<p><em>Note: The code above just stores the preference for the AutoSave option, you still have to create the code to manage the saving of data yourself.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://objcolumnist.com/2009/06/28/nsuserdefaults-preferences/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Helper Objects (Delegate and DataSource)</title>
		<link>http://objcolumnist.com/2009/06/14/helper-objects-delegate-and-datasource/</link>
		<comments>http://objcolumnist.com/2009/06/14/helper-objects-delegate-and-datasource/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 14:19:20 +0000</pubDate>
		<dc:creator>Spencer MacDonald</dc:creator>
				<category><![CDATA[Cocoa]]></category>
		<category><![CDATA[CocoaTouch]]></category>
		<category><![CDATA[Objective-C]]></category>

		<guid isPermaLink="false">http://objcolumnist.com/?p=69</guid>
		<description><![CDATA[Helper Objects are used throughout Cocoa and CocoaTouch, and usually take the form of a delegate or dataSource. They are commonly used to add functionality to an existing class without having to subclass it. In software engineering, the delegation pattern is a technique where an object outwardly expresses certain behaviour but in reality delegates responsibility [...]]]></description>
			<content:encoded><![CDATA[<p>Helper Objects are used throughout Cocoa and CocoaTouch, and usually take the form of a <em>delegate</em> or <em>dataSource</em>. They are commonly used to add functionality to an existing class without having to subclass it.</p>
<blockquote><p>In software engineering, the delegation pattern is a technique where an object outwardly expresses certain behaviour but in reality delegates responsibility for implementing that behavior to an associated object in an Inversion of Responsibility. The delegation pattern is the fundamental abstraction that underpins composition (also referred to as aggregation), mixins and aspects.</p>
<p>http://en.wikipedia.org/wiki/Delegation_pattern</p>
</blockquote>
<p>The most common use of helper objects in iPhone development is when using UITableViews. When you instantiate a UITableViewController this class is automatically assigned to be the delegate and dataSource of the table view it holds.</p>
<p><code><br />
self.tableView.delegate=self;<br />
self.tableView.dataSource=self;<br />
</code></p>
<p>The UITableView then calls the appropriate delegate method when it needs information, such as:</p>
<p><code><br />
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath<br />
</code></p>
<p>This ask the delegate, what is the height for the row at a given index path, so in your UITableViewController (the delegate) you would write the following, if you wanted the row to be 44 pixels high (the default).</p>
<p><code><br />
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{</p>
<p>      return 44;<br />
}<br />
</code></p>
<p><strong>Writing your own delegate.</strong></p>
<p>Most delegates are declared as a protocol, so the compiler knows that the delegate implements the required methods.</p>
<p><strong>Example:</strong></p>
<p>You have created a subclass of UITextView (e.g. OBCTextView), that you use in your application to enter both Tweets and SMS. You want to use the same class for both, BUT tweets have a character limit of 140 and SMS have a character limit of 160 (we will pretend that we are still in the 90s).</p>
<p>So we need to create a delegate that asks for the character limit.<br />
<code></p>
<p>- (NSInteger) charachterLimitForTextView: (OBCTextView *)textView;<br />
</code></p>
<p>As mentioned before this should be declared as a protocol<br />
<code><br />
@protocol OBCTextViewDelegate</p>
<p>- (NSInteger) charachterLimitForTextView: (OBCTextView *)textView;</p>
<p>@end<br />
</code></p>
<p>The OBCTextView would call this method like so:</p>
<p><code></p>
<p>-(void)askDelegateForCharachterLimit{</p>
<p>NSInterger charachterLimit = [delegate charachterLimitForTextView:self];</p>
<p>//Do something with character limit</p>
<p>}</p>
<p></code></p>
<p>In our SMS view controller we would declare that we implement the delegate protocol.<br />
<code></p>
<p>@interface OBCSMSViewController : UIViewController < OBCTextViewDelegate > {</p>
<p>}</p>
<p>@end<br />
</code></p>
<p>And then in the implementation file you would implement the following method<br />
<code></p>
<p>- (NSInteger) charchterLimitForTextView: (OBCTextView *)textView{<br />
       return 160;<br />
}</p>
<p></code></p>
<p>This method is required for OBCTextView to work so we should also add the key word <strong>@required</strong> to the protocol</p>
<p><code><br />
@protocol OBCTextViewDelegate</p>
<p>@required<br />
- (NSInteger)charchterLimitForTextView:(OBCTextView *)textView;</p>
<p>@end<br />
</code></p>
<p><strong>Optional methods</strong></p>
<p>In your delegate, you may also want to implement optional methods. So for this example we will ask for the text color. You can specify that a method is optional using <strong>@optional</strong>.</p>
<p>@protocol OBCTextViewDelegate</p>
<p>@required<br />
- (NSInteger)charachterLimitForTextView:(OBCTextView *)textView;</p>
<p>@optional<br />
- (UIColor *)textViewColorForTextView:(OBCTextView *)textView;</p>
<p>@end</p>
<p>As it is optional the delegate class (helper object), does not have to implement it. If it does not implement it, and we attempt to call it, the application will crash. So how do we know if we should call the method or not ? The answer is <em>respondsToSelector</em>.</p>
<p><em>respondsToSelector</em> allows you to ask an object at run time, if it implements a given selector. So for our example:</p>
<p><code></p>
<p>-(void)getTextColor{<br />
if( [delegate respondsToSelector: @selector(textViewColorForTextView:)] ){<br />
UIColor *textColor = [delegate textViewColorForTextView:self];<br />
//Do something with the text color</p>
<p>}</p>
<p>}</p>
<p></code></p>
<p>if your class wants to return a textview color, then you simply implement the method.</p>
<p><code></p>
<p>- (NSInteger)textViewColorForTextView:(OBCTextView *)textView{<br />
       return [UIColor redColor];<br />
}</p>
<p></code></p>
<p>So that finishes off this post on helper objects, and how you can create your own. As always this example was a simple one to make it easy to follow. You could probably implement the above using setter methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://objcolumnist.com/2009/06/14/helper-objects-delegate-and-datasource/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
