Determining equality, Writing to and reading from files – Apple WebObjects 3.5 User Manual
Page 190

Chapter 11
WebScript Programmer’s Quick Reference to Foundation Classes
190
Determining Equality
You can determine if two objects are equal using the
isEqual:
method. This
method returns YES if the receiver of the message and the specified object are
equal, and NO otherwise. The definition of equality depends on the object’s
type. For example, array objects define two arrays as equal if they contain the
same contents. For more information, see the
isEqual:
method descriptions later
in this chapter.
Writing to and Reading From Files
Strings, arrays, and dictionaries—three of the classes discussed in this chapter—
provide methods for writing to and reading from files. The method
writeToFile:atomically:
writes a textual description of the receiver’s contents to a
specified path name, and corresponding class-specific creation methods—
stringWithContentsOfFile:
,
arrayWithContentsOfFile:
, and
dictionaryWithContentsOfFile:
—create an
object from the contents of a specified file.
For example, the following code excerpt reads the contents of an error log stored
in a file, appends a new error to the log, and saves the updated log to the same
file:
id errorLog = [NSString stringWithContentsOfFile:errorPath];
id newErrorLog = [errorLog stringByAppendingFormat:@"%@: %@.\n",
timeStamp, @"premature end of file."];
[newErrorLog writeToFile:errorPath atomically:YES];
Writing to Files
To write to a file, use the method
writeToFile:atomically:
. It uses the
description
method
to obtain a human-readable string representation of the receiver and then writes
the string to the specified file. The resulting file is suitable for use with
classNameWithContentsOfFile:
methods. This method returns YES if the file is written
successfully, and NO otherwise.
If the argument for
atomically:
is YES, the string representation is first written to
an auxiliary file. Then the auxiliary file is renamed to the specified filename. If
the argument is NO, the object is written directly to the specified file. The YES
option guarantees that the specified file, if it exists at all, won’t be corrupted
even if the system should crash during writing.
When
writeToFile:atomically:
fails, it returns NO. If this happens, check the
permissions on the specified file and its directory. The most common cause of
write failures is that the process owner doesn’t have the necessary permissions
to write to the file or its directory. If the argument for
atomically:
is NO, it’s
sufficient to grant write permissions only on the file.