Archive for the ‘Cocoa’ Category

When A Café Is Not A Café – A Short Lesson In Unicode Featuring NSString

Thursday, March 8th, 2012

Let’s start with two exotic strings (console output is in the code comments):

NSString* apples = NSGetFrenchWord();
NSString* oranges = NSGetFrenchWord();
 
NSLog(@"apples == '%@'", apples); 
//apples == 'café'
NSLog(@"oranges == '%@'", oranges); 
//oranges == 'café'

They look identical, but looks can be deceiving.

NSLog(@"isEqual? %@", [apples isEqual:oranges] ? @"YES" : @"NO");
//isEqual? NO
NSLog(@"[apples length] == %lu", [apples length]);
//[apples length] == 4
NSLog(@"[oranges length] == %lu", [oranges length]);
//[oranges length] == 5

(more…)

Gotchas With Grand Central Dispatch (libdispatch) And Blocks

Friday, March 2nd, 2012

GCD is a nice replacement for the old performSelectorInBackground:withObject: and performSelectorOnMainThread:withObject:waitUntilDone: methods and NSOperation. It’s also a nice supplement to NSThread.

However, I think it was over-hyped a little bit by Apple when it was first released. You probably have all these random deadlocks and race conditions and stuff whenever you use multiple threads, but GCD is soooooo good that you don’t have to worry about that anymore. Just use these magic blocks.

The problem is that concurrent programming is notoriously hard to get right. Maybe GCD helps to make it easier, but It doesn’t solve all of your problems. In fact, GCD and blocks introduce some problems of their own. This article will focus on some of those problems.
(more…)

Const Correctness For NSString (And Pointers In General)

Friday, December 16th, 2011

So you’re implementing a new notification and you want the name to be a constant. Easy, right?

const NSString* VTMyNewNotification;

If that’s how you do constants, you’re not doing it quite right. Try assign a new value to the alleged constant and watch in horror as the compiler doesn’t stop you.

This is because when you type const NSString*, the compiler interprets that as a pointer to a constant NSString. NSString is already an immutable object, so making a constant NSString doesn’t do anything except maybe cause some compiler errors/warnings later when you try to use it. What you’re really after is a constant pointer to an NSString. It’s ever so subtly different, and written like so:

NSString* const VTMyNewNotification;

Don’t feel bad. It’s a common mistake. I used to do it until Rob Napier schooled me, and now I’m passin’ on the learnin’ to you.

Using Blocks (i.e. Closures) To Improve Transactional Code

Sunday, November 21st, 2010

I stumbled across a nice article by Jonathan Dann about using blocks to improve transactional code.

When I say "transactional" code, I mean code that has an opening, a middle, and a closing, where the opening and the closing have to be matched. You see it in a few places in Cocoa, such as:

  • KVO:
    1. willChangeValueForKey:
    2. change the value
    3. didChangeValueForKey:
  • NSGraphicsContext:
    1. saveGraphicsState
    2. do some drawing
    3. resoreGraphicsState
  • NSFileWrapper:
    1. open a file
    2. read/write to it
    3. close the file

I’m going to show you a "before and after" comparison of a function that uses NSGraphicsContext and NSAffineTransformation.
(more…)

How Cocoa Bindings Work (via KVC and KVO)

Friday, November 5th, 2010

Cocoa bindings can be a little confusing, especially to newcomers. Once you have an understanding of the underlying concepts, bindings aren’t too hard. In this article, I’m going to explain the concepts behind bindings from the ground up; first explaining Key-Value Coding (KVC), then Key-Value Observing (KVO), and finally explaining how Cocoa bindings are built on top of KVC and KVO.
(more…)

AspectObjectiveC framework 1.0 Release

Friday, October 29th, 2010

I’ve (finally) released version 1.0 of AOC. I could go on improving it forever, but it’s good enough to release so I’m going to set it free in the wild. Give it a spin, tell your neighbors, and let me know what you think.

Manual:
http://www.tomdalling.com/aoc_doc_mirror/

API Docs:
http://www.tomdalling.com/aoc_doc_mirror/api/

Source/project:
http://github.com/tomdalling/AspectObjectiveC

Download (framework compiled for i386 and x86_64):
http://github.com/…/AspectObjectiveC.framework-v1.0.zip (direct)
http://github.com/tomdalling/AspectObjectiveC/downloads (github download page)

Why performSelector: Is More Dangerous Than I Thought

Friday, May 14th, 2010

I fixed a rather nasty bug today in AspectObjectiveC. One particular unit test would crash with EXC_BAD_ACCESS every time. After learning far more about registers and ABIs than I ever wanted to know (thanks, Greg Parker), it dawned on me that performSelector: was corrupting memory. It was particularly hard to track down because the crash would happen a couple of lines after the call to performSelector:, when the corrupted memory was actually accessed.

I’ve never had a problem with performSelector: before, but this time I was using it a little differently. The return value of the selector was an NSRect.

Now for the gory explanation.

(more…)

Video: AspectObjectiveC In Five Minutes

Saturday, March 20th, 2010

Here’s a quick video about AspectObjectiveC, and what it can do. The code is available from github. I should also mention that AspectObjectiveC isn’t ready for release just yet.

Side Project: AspectObjectiveC

Thursday, March 11th, 2010

I’ve started a new side project called AspectObjectiveC on github. It’s a little aspect-oriented programming framework for objective-c.

In a nutshell, it allows you to run arbitrary code before, after, or instead of any method at runtime. You can modify arguments before they enter the method, modify the return value of the method, or completely replace the method’s implementation without touching the class’ source code. This includes classes that you don’t have the source code for (e.g. other frameworks). It’s released under the MIT license, even though it doesn’t mention it anywhere yet.

It’s still rough, but it’s working (on my machine :) ). If you want to try it out then build the framework target and whack it into an app as a private framework. It’s got no documentation yet, but the public headers only expose one protocol (AOCAdvice) and one class (AOCAspectManager) with two methods, so it’s pretty intuitive. You can check the unit tests for example usage too.

If you want to contribute code, that’d be great. If you want to test it out on platforms other than OSX >= 10.5, i386 with gcc, that would also be great. Feel free to shoot me an email about it.

MD5 Hashes in Cocoa

Thursday, September 24th, 2009

Let’s jump straight into the code:

#import <commoncrypto /CommonDigest.h>
 
NSString* MD5StringOfString(NSString* inputStr)
{
	NSData* inputData = [inputStr dataUsingEncoding:NSUTF8StringEncoding];
	unsigned char outputData[CC_MD5_DIGEST_LENGTH];
	CC_MD5([inputData bytes], [inputData length], outputData);
 
	NSMutableString* hashStr = [NSMutableString string];
	int i = 0;
	for (i = 0; i < CC_MD5_DIGEST_LENGTH; ++i)
		[hashStr appendFormat:@"%02x", outputData[i]];
 
	return hashStr;
}

Now for the explanation.
(more…)