Cocoa Fundamentals Guide

Page 90

CHAPTER 2

Cocoa Objects

This isEqual: method first checks for pointer equality, then class equality, and finally invokes an object comparator whose name indicates the class of object involved in the comparison. This type of comparator, which forces type-checking of the object passed in, is a common convention in Cocoa; the NSString isEqualToString: and the NSTimeZone isEqualToTimeZone: are but two examples. The class-specific comparator—isEqualToWidget: in this case—performs the checks for name and data equality. In all isEqualToType: methods of the Cocoa frameworks nil is not a valid argument and implementations of these methods may raise an exception upon receiving a nil. However, for backwards compatibility, isEqual: methods of the Cocoa frameworks do accept nil, returning NO.

Object Mutability Cocoa objects are either mutable or immutable. You cannot change the encapsulated values of immutable objects; once such an object is created, the value it represents remains the same throughout the object’s life. But you can change the encapsulated value of a mutable object at any time. The following sections explain the reasons for having mutable and immutable variants of an object type, describes the characteristics and side-effects of object mutability, and recommends how best to handle objects when their mutability is an issue.

Why Mutable and Immutable Object Variants? Objects by default are mutable. Most objects allow you to change their encapsulated data through “setter” accessor methods. For example, you can change the size, positioning, title, buffering behavior, and other characteristics of an NSWindow object. A well-designed model object—say, an object representing a customer record—requires setter methods to change its instance data. The Foundation framework adds some nuance to this picture by introducing classes that have mutable and immutable variants. The mutable subclasses are typically subclasses of their immutable superclass and have “Mutable” embedded in the class name. These classes include the following: NSMutableArray NSMutableDictionary NSMutableSet NSMutableIndexSet NSMutableCharacterSet NSMutableData NSMutableString NSMutableAttributedString NSMutableURLRequest

Note: Except for NSMutableParagraphStyle in the Application Kit, the Foundation framework currently defines all explicitly named mutable classes. However, any Cocoa framework can potentially have its own mutable and immutable class variants. Although these classes have atypical names, they are closer to the mutable norm than their immutable counterparts. Why this complexity? What purpose does having an immutable variant of a mutable object serve?

90

Object Mutability 2008-11-19 | © 2008 Apple Inc. All Rights Reserved.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.