Categories

Foundation

  • May 30, 2011

    Objective-C era

    Classes for fetching and parsing XML or JSON via HTTP

    In this post I show two reusable classes for fetching data via HTTP: one that parses the result as XML and another that parses as JSON. These are relatively simple tasks but due to the number of required steps, they can become tiresome if you don't have robust, reusable code for the task. These classes will work on iOS or on the Mac but the optional error alerts and password dialogs are only implemented for iOS.

    Read article

  • Oct 6, 2010

    Objective-C era

    Testing if an arbitrary pointer is a valid object pointer

    In this post, I look at an approach for testing if an arbitrary pointer is a pointer to a valid Objective-C object. The result from the test is not absolutely accurate and can interfere with gdb debugging if the pointer isn't a valid memory location, so this is not something you'd want to do often (and certainly not in production code). But it can be a handy debugging tool for when you're staring blindly at memory you didn't allocate.

    Read article

  • Sep 20, 2010

    Objective-C era

    Minimalist Cocoa programming

    In this post, I build and run a Cocoa Mac application on the command-line. This might not sound like a very difficult goal but I'll attempt to follow an additional constraint: use as few tools, components, classes and even lines of code as possible; truly minimalist Cocoa programming. The goal is to create an application that qualifies as a proper Mac application (including a menubar and a window) but without using Xcode, without an Info.plist file, without NIB files, without Interface Builder and without even using a text editor other than the Terminal itself.

    Read article

  • Jun 10, 2010

    Objective-C era

    Sorting an NSMutableArray with a random comparison method

    If you sorted an NSMutableArray with a comparison method that randomly returns either higher or lower, would the result be an even, random distribution? Spoiler: no it won't but the actual distribution is interesting nonetheless. I'll show you what would happen if you did sort this way (and also show you how to correctly randomize an array if you did want an even distribution).

    Read article

  • Jun 2, 2010

    Objective-C era

    Avoiding deadlocks and latency in libdispatch

    The system-wide thread pool of libdispatch's global queue is an easy way to efficiently manage concurrent operations but it is not the solution to all threading problems and it is not without its own class of problems. In this post I look at deadlocks and latency problems that are inherent in thread-pool based solutions like libdispatch's global concurrent queue so that you will know when you should use this option and when you need something else.

    Read article

  • May 6, 2010

    Objective-C era

    Finding or creating the application support directory

    A simple post this week but one which optimizes a common task: locating the application support directory for the current application, creating it if it doesn't exist. The result makes accessing the current application's support directory a single line and provides a structure for locating and creating folders at other standard locations with similar ease.

    Read article

  • Apr 27, 2010

    Objective-C era

    Porting a Mac program to Windows using The Cocotron

    In this last of three posts about porting a Mac application to Windows, I look at the steps involved in setting up The Cocotron with a remote debugging session between Xcode and the application running on Windows. I'll also talk about the code that didn't "just work" and some of the approaches I used to fix the program and get it working.

    Read article

  • Apr 21, 2010

    Objective-C era

    Design of a multi-platform app using The Cocotron

    In this post, I'll talk about how multi-platform applications are structured and talk about some of the different ways that applications separate core logic from platform specific behaviors. I'll talk about how using a porting layer like The Cocotron fits into these designs and why using The Cocotron doesn't necessarily mean that you're ignoring best-practice or creating a second-class application.

    Read article

  • Feb 21, 2010

    Objective-C era

    Resolving a path containing a mixture of aliases and symlinks

    Resolving symlinks in a path is very easy in Cocoa (it can be done in a single statement) but aliases require more work. Additionally the commands for resolving symlinks and aliases are incompatible with each other — meaning that you can resolve a path containing symlinks or aliases but not a mixture of the two. In this post, I present a category on NSString that will allow you to resolve a path containing any combination of symlinks or aliases as simply as resolving symlinks alone.

    Read article

  • Jan 25, 2010

    Objective-C era

    5 key-value coding approaches in Cocoa

    Key-value coding (KVC) is a way of decoupling a generic action from the specific properties it may need to act upon. It is most commonly associated with the NSKeyValueCoding protocol but there are a number of other ways to achieve the same effect. In this post, I look at why key-value coding is important and show you 5 different ways — each with their own particular advantages — to implement this pattern.

    Read article

  • Jan 17, 2010

    Objective-C era

    What is a meta-class in Objective-C?

    In this post, I look at one of the stranger concepts in Objective-C — the meta-class. Every class in Objective-C has its own associated meta-class but since you rarely ever use a meta-class directly, they can remain enigmatic. I'll start by looking at how to create a class at runtime. By examining the "class pair" that this creates, I'll explain what the meta-class is and also cover the more general topic of what it means for data to be an object or a class in Objective-C.

    Read article

  • Nov 30, 2009

    Objective-C era

    Writing a parser using NSScanner (a CSV parsing example)

    Comma-separated value (CSV) files are one of the most commonly used data formats for exchanging rows of simple data. There are many implementations of CSV parsing for Cocoa strings but the purpose of this post is to use the example of an RFC4180 compliant CSV parser implementation to show you the basics of writing a recursive descent parser for importing data into your Cocoa applications.

    Read article

  • Nov 14, 2009

    Objective-C era

    A drop-in fix for the problems with NSHost

    As pointed out by Mike Ash in his recent Friday Q&A 2009-11-13: Dangerous Cocoa Calls, NSHost is not thread-safe for use outside of the main thread and due to potentially slow, synchronous network access is not really suitable for use on the main thread either. Fortunately, in Cocoa there are often ways to transparently fix classes that don't work as they should. In this post, I'll show you how you can transparently patch NSHost using a drop-in solution and provide a non-blocking solution for NSHost lookups.

    Read article

  • Oct 18, 2009

    Objective-C era

    How blocks are implemented (and the consequences)

    This post is a look at how clang implements blocks and how this implementation leads to a number of strange behaviors including local variables that end up global, Objective-C objects allocated on the stack instead of the heap, C variables that behave like C++ references, Objective-C objects in non-Objective-C languages, copy methods that don't copy and retain methods that don't retain.

    Read article

  • Sep 28, 2009

    Objective-C era

    Optimizing the loading of a very large table on the iPhone

    In this post, I look at a UITableView on the iPhone which loads its data from a server and look at how its performance scales from single rows to tens of thousands of rows. I'll examine which aspects of the iPhone scale well and which become a burden as a displayed dataset moves from trivially sized to large sizes.

    Read article

  • Aug 9, 2009

    Objective-C era

    Safe, threaded design and inter-thread communication

    The Foundation framework provides all the tools you need for inter-thread communication — without needing to handling locks and synchronization yourself. I'll show you Cocoa's tools for inter-thread communication, notifications and easy synchronization — including far simpler code for posting NSNotifications on the main thread than the Cocoa documentation suggests.

    Read article

  • Jul 23, 2009

    Objective-C era

    Temporary files and folders in Cocoa

    If you need to use temporary files in your application and you search the Cocoa documentation for "temporary file", you're unlikely to find anything that explains how to create one. Since temporary files and folders are subject to a number of security issues and race conditions when done wrong, it is important to know the correct way to create them. I'll show you some code that you can copy and paste into your applications to create temporary files and folders safely.

    Read article

  • Jul 13, 2009

    Objective-C era

    A simple, extensible HTTP server in Cocoa

    HTTP is one of the simpler protocols to implement for communication between computers. On the iPhone, since there are no APIs for data synchronization or file sharing, embedding an HTTP server is one of the best ways to transfer data from your iPhone application to a computer. In this post I'll show you how to write your own simple but extensible HTTP server. The server classes will also work on Mac OS X (Cocoa un-Touched).

    Read article

  • Jul 6, 2009

    Objective-C era

    HashValue: an object for holding MD5 and SHA hashes

    Hash values are small, convenient values that you can generate from larger blocks of data for easy indexing, sorting and tracking. The traditional approach for generating MD5 and SHA hashes on Unix platforms to is to use command-line programs like openssl and md5. Apple provide easier approaches in the CommonCrypto library: here's how to use it, along with an NSValue subclass to wrap the result for interoperability with other Cocoa classes.

    Read article

  • Jun 23, 2009

    Objective-C era

    Verifying that a string contains an email address using NSPredicate

    To celebrate the official release of iPhone OS 3.0 this week, I will show you how to verify that an NSString contains a syntactically valid email address using NSPredicate — a class that joins the iPhone SDK 3.0 as part of the Core Data additions. This code will work on Mac OS X too since, as with the rest of Core Data, NSPredicate has been part of Mac OS X since 10.4 (Tiger).

    Read article

  • Jun 3, 2009

    Objective-C era

    Base64 encoding options on the Mac and iPhone

    On Unix platforms, a common approach for Base64 encoding is to use libcrypto (the OpenSSL library). However, like most C libraries, you need to wrap it to integrate with Objective-C data types (like NSData and NSString) and it isn't available on the iPhone. I'll show you how to handle base64 encoding/decoding with OpenSSL and without so you can handle the Mac and iPhone equally.

    Read article

  • May 25, 2009

    Objective-C era

    Simple methods for date formatting and transcoding

    There is no single-line method for converting between formatting date strings and date objects in Cocoa — the API opts for flexibility rather than simplicity. Unfortunately, this combines with documentation that omits, misdirects and occasionally misinforms, making NSDateFormatter one of the more confusing classes for new Cocoa programmers. In this post, I'll try to address some of the documentation issues and I'll present some methods that will turn NSDate into a formatted string or convert between date strings in a single method.

    Read article

  • May 10, 2009

    Objective-C era

    Variable argument lists in Cocoa

    This week I'll talk about methods that take variable numbers of arguments, also known as variadic methods. I'll show you the Objective-C syntax and implementation, give a quick rundown of the ways that Cocoa classes provide variable argument support and I'll also show you a way to fake va_list parameters to handle Cocoa's variadic method equivalents at runtime.

    Read article

  • May 4, 2009

    Objective-C era

    Invoking other processes in Cocoa

    Invoking other processes is a good way to handle some low-level tasks on the Mac. I'll show you some simple ways to invoke processes and parse their outputs in Cocoa apps as well as some advanced tricks like running a process with administrator privileges.

    Read article

  • Mar 28, 2009

    Objective-C era

    Using NSKeyedArchiver to archive a C linked-list

    NSKeyedArchiver provides some support for archiving C primitive types but provides no support for pointers to C structs. I'll show you how you can archive a linked list of C structs, despite the lack of support in NSKeyedArchiver.

    Read article

  • Feb 7, 2009

    Objective-C era

    Breadth-first traversal of a graph of Objective-C objects

    If you have a collection of interconnected objects in Objective-C, what is the best way to traverse them all in order from nearest to furthest? Are the NSMutableSet methods good for tracking already-visited nodes? How much overhead does an NSMutableArray FIFO queue impose relative to a depth-first search (which doesn't require a FIFO queue)? Does NSMutableArray perform better if objects are pushed onto the front, or the back? In this post, I present answers to these questions and more.

    Read article

  • Feb 1, 2009

    Objective-C era

    Interprocess communication: snooping, intercepting and subverting

    When Xcode is running, Interface Builder seems to magically know which classes, methods and variables are available. Where does Interface Builder get this information? How can you recreate this effect when editing source files in an external editor without Xcode running? This is the story of how I investigated the communication between Xcode and Interface Builder, so that I could recreate it for myself.

    Read article

  • Jan 5, 2009

    Objective-C era

    Serving an NSManagedObjectContext over an NSConnection

    In this post, I'll show you how you can serve a Core Data document over a network using NSConnection. This arrangement will never be as efficient or safe as writing your own code to communicate the data over the network but the promise of transparent and automatic networking seemed too tempting to pass up.

    Read article

  • Dec 18, 2008

    Objective-C era

    OrderedDictionary: Subclassing a Cocoa class cluster

    The default Cocoa collection classes are highly capable but there are situations where you may need to override them to alter their functionality. I'll explain when and how you should do this with an example class: OrderedDictionary (an NSMutableDictionary subclass that maintains ordering of its keys).

    Read article

  • Nov 16, 2008

    Objective-C era

    Singletons, AppDelegates and top-level data.

    If you require only a single instance of an object in your application, where should it go? How should you control and manage it? Here are some different approaches, their implementations, their strengths and their weaknesses.

    Read article

  • Nov 10, 2008

    Objective-C era

    Simplifying your code using NSDictionary

    Computers programs are good at mindless repetitive tasks, they are not good at broad decision trees. In this post, I will show you a way of eliminating conditionals from your code that are based on program state by using an array of NSDictionary objects to maintain state.

    Read article

  • Oct 31, 2008

    Objective-C era

    Using libxml2 for XML parsing and XPath queries in Cocoa

    NSXMLDocument is the normal tree-based XML parser in Cocoa. But if you're writing for the iPhone, this class isn't available. Even on the Mac, sometimes you want tree-based parsing without the full overhead of NSXMLDocument. Here's how to use libxml2 to perform tree-based parsing in a Cocoa-friendly way.

    Read article

  • Oct 10, 2008

    Objective-C era

    WorldTimeConverter: Dates and timezones in Cocoa

    Recently, I searched for a world time converter — one that would handle future dates as well as the current time. There are web versions but I didn't find a genuine Mac OS X application that matched my desires. How hard could it be? The answer is 1 subtraction — provided you can find the right values to subtract. Read on and I'll show you how it's done.

    Read article

  • Sep 20, 2008

    Objective-C era

    A Cocoa application driven by HTTP data

    Here's a tiny application that queries a webpage via HTTP, parses and searches the response and presents the results in a neatly formatted window. In essence, it's what many Dashboard widgets and iPhone apps do but I'll show you how to do it in a regular Cocoa application.

    Brought to you by FuelView, an iPhone application I wrote for fetching FuelWatch information in Western Australia.

    Read article

  • Aug 9, 2008

    Objective-C era

    NSArray or NSSet, NSDictionary or NSMapTable

    Some types of data can be held in more than one kind of collection. Unordered objects that are already guaranteed unique can be sensibly held in an NSArray or an NSSet. Anything an NSDictionary can hold can be held in an NSMapTable. In this post, I measure the performance of creating and using these different options to help you choose which one is right for you.

    Read article

  • Jul 27, 2008

    Objective-C era

    Key Value Information

    NSKeyValueCoding is used throughout Cocoa (Bindings, Core Data, Collections and more) but despite being a dynamic way of connecting to an object, it doesn't provide dynamic information about its own operation — which keys an object supports or the custom methods used to get and set values. This post will look at how NSKeyValueCoding works and show you how to get supported keys and their methods for any class or object.

    Read article

  • Jul 6, 2008

    Objective-C era

    NSMapTable: more than an NSDictionary for weak pointers

    NSMapTable is collection class that was introduced in Mac OS X 10.5 (Leopard). At first glance, it would appear to be most useful as an NSDictionary replacement that can choose between "strong" and "weak" pointers. In this post, I'll show you why it is also useful outside garbage collection and how it can do things that NSDictionary can't (or shouldn't) do.

    Read article

  • May 15, 2008

    Objective-C era

    Objective-C 2.0: Fast enumeration clarifications

    Fast enumeration in Objective-C 2.0 is a doubly useful addition: it results in code that looks better and runs faster. Its documentation though, still contains a few points which are ambiguous or misleading. Here are some clarifications that I've uncovered.

    Read article

  • May 9, 2008

    Objective-C era

    Square Root: Numerical fun with NSDecimalNumber

    NSDecimalNumber is a powerful Foundation class that holds high precision base 10 numbers. The default class only provides basic arithmetic operators, leaving you to write any advanced operations that you need. This is an example that implements a square root using NSDecimalNumber.

    Read article

  • Apr 14, 2008

    Objective-C era

    Type punning isn't funny: Using pointers to recast in C is bad.

    A very common C technique for reinterpreting data types has the potential to cause nasty bugs. Apple knows this, which is why the implementation of NSRectToCGRect (correctly) doesn't do what the documention claims. I show you a technique to perform reinterpret casts safely in your own code.

    Read article

  • Mar 19, 2008

    Objective-C era

    Construct an NSInvocation for any message, just by sending

    I will show you how to use object forwarding to record any message in an NSInvocation, by simply sending the message to an object. Unlike techniques shown elsewhere, this will allow you to record any message, including NSObject messages and even the forwarding messages themselves.

    Read article