macdevcenter.com
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button Programming With Cocoa

Strings in Cocoa, Part 2

07/13/2001

This column is a continuation from the last on how to work with strings in Cocoa. In the last column, we covered a lot of the basics about strings that you would learn with any programming language/environment.

We started with the essential step of first creating a string with the variety of methods provided to us by NSString, and then went on to learn how we can use these strings. We touched on some more OOP with class clusters, and also some very simple file I/O with strings. Additionally, much time was spent discussing comparison, search, and substring extraction methods.

Today, I want to continue along this course by telling you about NSString's path manipulation tools, and NSString's subclass, NSMutableString, which allows us to create strings whose contents we can edit after their creation -- something that was not possible with NSString alone. I will finally conclude this column with a bit of string miscellany. With that said, let's get started!

Working with path strings

In the previous column I showed you how we can write strings to a text file, and create new strings from a text file. In these situations, we represented file locations (paths) as strings. This will also be the case any time we work with files, that is, the file paths will be NSString object strings.

The string representation of file locations and paths is standard in Cocoa, and the NSString class provides us with a set of methods that allows us to manipulate file path strings. These methods let us do things like replace the tilde in a path with an absolute path, resolve symbolic links, extract path components into new string, and work with file extensions.

Comment on this articleThis concludes our detailed look at strings for the moment. Is there anything that should be discussed before we move on to the collections classes of Cocoa?
Post your comments

Also in Programming With Cocoa:

Understanding the NSTableView Class

Inside StYNCies, Part 2

Inside StYNCies

By now we all know Mac OS X is built on top of Unix (oh man, would I love to go on about how Apple scored big with that move!), and as such, directories and files are organized the Unix way, and manipulated in the Unix way. There are several things you should know about this that are different from the normal Macintosh way of doing things (I'm sure many of you know about this, but it never hurts to cover the fundamentals, so please bear with me).

In the Unix way of doing things, the path to a user's home directory is abbreviated with a tilde ("~"). This is a very useful shorthand for moving around in the file system. For example, my home directory on my lime green iBook, is /Users/mike/ in the expanded way of doing things, or in the shorthand it's simply ~. However, a tilde in a path string will not be recognized as a valid path, so we have to expand the tilde using the - stringByExpandingTildeInPath method. In the following example:

NSString *shortPath = @"~/textFile.txt";
NSString *absolutePath = [shortPath stringByExpandingTildeInPath];

the - stringByExpandingTildeInPath method would return a string that is the expanded, absolute path to textFile.txt, with the current user's home directory path put in place of the tilde. The new path is now /Users/mike/textFile.txt. We can also accomplish the reverse, where a the path to a user's home directory is abbreviated with a tilde. The method we use to do this is -stringByAbbreviatingWithTildeInPath:

NSString *path = [absolutePath stringByAbbreviatingWithTildeInPath];

which would set path to ~/textFile.txt. Notice that in all of these methods (and all the ones we talked about last time) the first word is "string", which means a string is returned by the receiver of any string… message. This syntax is common throughout the Cocoa frameworks and we will see it with arrays, numbers, dictionaries, and so on. Cocoa's method names are designed to be as unambiguous as possible (this does make for more typing, but I think readable, unambiguous code is worth it).

File extensions are also prevalent in Unix (to many a Mac user's disdain). The file extension is the one, two, three, or more letter suffix following a file's name with a period in between the name and the extension (the single period is not considered to be a part of the extension in Cocoa). We can obtain the file extension as a new string object by invoking the - pathExtension method on some path string, which returns an NSString objects containing the path extension, less the period.

NSString *path = @"~/textFile.txt";
NSString *pathExtension = [path pathExtension];

The string pathExtension would be "txt". The period is removed. If there is no period indicating a path extension, an empty string is returned. If there is no file, an empty string is also returned.

Naturally, there's a method to do the reverse; that is, add a path extension where there once was none. This is done using the - stringByAppendingPathExtension: method. If we had a path string /Users/mike/textFile, we could add the ".txt" path extension by doing the following:

NSString *path = @"Users/mike/textFile";
path = [path stringByAppendingPathExtension:@"txt"];

The path would then be /Users/mike/textFile.txt. Note that in this example we stored the returned path over the old path in the variable path.

If we wanted to get rid of the path extension altogether, leaving us with just a path and file name, we would use the method - stringByDeletingPathExtension. Using our original path /Users/mike/textFile.txt:

path = [path stringByDeletingPathExtension];

the path would then be /Users/mike/textFile. The method returns the original string, less the path extension (including the period directly preceding the path extension).

Another useful set of path manipulation tools in NSString are those that let us work with the components of a path, the individual directory names, and the file name at the end. The first of these methods is -pathComponents. Seems easy enough. What this does is take a path string and split it up at each of the slashes into several strings, which are then put into an NSArray object. We haven't talked about NSArray yet, but it's nothing more than a standard array, Cocoa style. So, if we had the following path:

NSString *thisColumn = @"/Users/mike/Documents/Cocoa_Column/Column8.doc"

(I admit it, I'm fairly fond of Word.) -pathComponents would split it up and dump it into an array like this:

NSArray *theComponents = [thisColumn pathComponents];

The resulting array looks like this:

Array Index Path Component
0 Users
1 mike
2 Documents
3 Cocoa_Column
4 Column8.doc

This allows us to go in and completely pick apart a path with easy access to any of the directories or the file. If our desires are of a simpler nature, we can use any of the methods that let us work with the last component, which is usually enough. They are -lastPathComponent, -stringByAppendingPathComponent:, and -stringByDeletingLastPathComponent. They all work as you would expect them to from the name. If they were given the same path as above,

NSString *thisColumn = @"/Users/mike/Documents/Cocoa_Column/Column8.doc"

then we could do the following things with it:

NSString *lastComponent = [thisColumn lastPathComponent];
NSString *pathLessFilename = [thisColumn stringByDeletingLastPathComponent];
NSString *originalPath = [pathLessFilename stringByAppendingPathComponent:lastComponent];

In the end, originalPath is equivalent to thisColumn. What happened was in the first line we made a new string, which was the last path component returned by lastPathComponent (aren't these method names spiffy?) of thisColumn, "Column8.doc". In the next line, we created another string, which is the directory in which the Column8.doc lives, and then in the last line we combine the two to reconstruct the original path.

So, you've seen a small handful of the methods available for working with paths. You can see the whole lot of them in the NSString class reference; naturally, the class reference goes into much more detail than we've seen here.

Onward to those strings that can mutate!

Pages: 1, 2

Next Pagearrow