Home > Articles > Programming > C/C++

Objective-C Boot Camp

This chapter is from the book

Properties

Properties expose class variables and methods to outside use through what are called “accessor methods” (that is, methods that access information). Using properties might sound redundant. After all, the class definition shown in Listing 3-1 already announces public methods. So why use properties? It turns out that there are advantages to using properties over hand-built methods, not the least of which are dot notation and memory management.

Dot Notation

Dot notation allows you to access object information without using brackets. Instead of calling [myCar year] to recover the year instance variable, you use myCar.year. While this may look as if you’re directly accessing the year instance variable, you’re not. Properties always invoke methods. These, in turn, can access an object’s data. So you’re not, strictly speaking, breaking an object’s encapsulation as properties rely on these methods to bring data outside the object.

Due to method hiding, properties simplify the look and layout of your code. For example, you can access properties to set a table’s cell text via

myTableViewCell.textLabel.text = @"Hello World";

rather than the more cumbersome

[[myTableViewCell textLabel] setText:@"Hello World"];

The property version of the code is more readable and ultimately easier to maintain. Admittedly, Objective C 2.0’s dot notation may initially confuse C programmers who are used to using dots for structures instead.

Properties and Memory Management

Properties can help simplify memory management. You can create properties that automatically retain instance variables for the lifetime of your objects and release them when you set those variables to nil. Setting a retained property ensures that memory will not be released until you say so. Of course, properties are not a magic bullet. They must be defined and used properly.

Assigning an object to a retained property means you’re guaranteed that the objects will be available throughout the tenure of your ownership. Listing 3-2 did not retain its make and model. If those objects were released somewhere else in an application, the pointers to the memory that stored those objects would become invalid. At some point, the application might try to access that memory and crash. By retaining objects, you ensure that the memory pointers remain valid.

The arrayWithObjects: method normally returns an autoreleased object, whose memory is deallocated at the end of the event loop cycle. (See Chapter 1, “Introducing the iOS SDK,” for details about autorelease pools. A deeper discussion about memory management follows later in this chapter.) Assigning the array to a retained property means that the array will stick around indefinitely. You retain the object, preventing its memory from being released until you are done using it.

self.colors = [NSArray arrayWithObjects:
    @"Gray", @"Silver", @"Black", nil];

When you’re done using the array and want to release its memory, set the property to nil. This approach works because Objective-C knows how to synthesize accessor methods, creating properly managed ways to change the value of an instance variable. You’re not really setting a variable to nil. You’re actually telling Objective-C to run a method that releases any previously set object and then sets the instance variable to nil. All this happens behind the scenes. From a coding point of view, it simply looks as if you’re assigning a variable to nil.

self.colors = nil;

Do not send release directly to retained properties (for example, [self.colors release]). Doing so does not affect the colors instance variable assignment, which now points to memory that is likely deallocated. When you next assign an object to the retained property, the memory pointed to by self.colors will receive an additional release message, likely causing a double-free exception.

Creating Properties

There are two basic styles of properties: read-write and read-only. Read-write properties, which are the default, let you modify the values you access; read-only properties do not. Use read-only properties for instance variables that you want to expose, without providing a way to change their values. They are particularly handy for properties that are generated by algorithm from several instance variables or from device sensors, such as a device orientation.

The two kinds of accessor methods you must provide are called setters and getters. Setters set information; getters retrieve information. You can define these with arbitrary method names or you can use the standard Objective-C conventions: The name of the instance variable retrieves the object, while the name prefixed with “set” sets it. Objective-C can even synthesize these methods for you. For example, if you declare a property such as the Car class’s year in your class interface, as such

@property (assign) int year;

and then synthesize it in your class implementation with

@synthesize year;

you can read and set the instance variable with no further coding. Objective-C builds two methods that get the current value (that is, [myCar year]) and sets the current value (that is, [myCar setYear:1962]) and adds the two dot notation shortcuts:

myCar.year = 1962;
NSLog(@"%d", myCar.year);

To build a read-only property, declare it in your interface using the readonly attribute. Read-only properties use getters without setters. For example, here’s a property that returns a formatted text string with car information:

@property (readonly) NSString *carInfo;

Although Objective-C can synthesize read-only properties, you can also build the getter method by hand and add it to your Class implementation. This method returns a description of the car via stringWithFormat:, which uses a format string ala sprintf to create a new string:

- (NSString *) carInfo
{
    return [NSString stringWithFormat:
        @"Car Info\n    Make: %@\n    Model: %@\n    Year: %d",
        self.make ? self.make : @"Unknown Make",
        self.model ? self.model : @"Unknown Model",
        self.year];
}

This method now becomes available for use via dot notation. Here’s an example:

CFShow(myCar.carInfo);

If you choose to synthesize a getter for a read-only property, you should use care in your code. Inside your implementation file, make sure you assign the instance variable for that property without dot notation. Imagine that you declared model as a read-only property. You could assign model with

model = @"Prefect";

but not with

self.model = @"Prefect";

The latter use attempts to call setModel:, which is not defined for a read-only property.

Creating Custom Getters and Setters

Although Objective-C automatically builds methods when you @synthesize properties, you may skip the synthesis by creating those methods yourself. For example, you could build methods as simple as the following. Notice the capitalization of the second word in the set method. By convention, Objective-C expects setters to use a method named setInstance:, where the first letter of the instance variable name is capitalized.

-(int) year
{
    return year;
}

- (void) setYear: (int) aYear
{
    year = aYear;
}

When building your own setters and getters, you might add some basic memory management. The following methods retain new items and release previous values:

- (NSString *) model
{
    return model;
}

- (void) setModel: (NSString *) newModel
{
    if (newModel != model) {
        [model release];
        model = [newModel retain];
    }
}

You could go even further by building more complicated routines that generate side effects upon assignment and retrieval. For example, you might keep a count of the number of times the value has been retrieved or changed, or send in-app notifications to other objects. The Objective-C compiler remains happy so long as it finds, for any property, a getter (typically named the same as the property name) and a setter (usually setName:, where Name is the name of the property). What’s more, you can bypass any Objective-C naming conventions by specifying setter and getter names in the property declaration. This declaration creates a new Boolean property called forSale and declares a custom getter/setter pair. As always, you add any property declarations to the class interface:

@property (getter=isForSale, setter=setSalable:) BOOL forSale;

Then you synthesize the methods as normal in the class implementation. The implementation is typically stored in the .m file that accompanies the .h header file.

@synthesize forSale;

If you have more than one item to synthesize, you can add them in separate @synthesize statements or combine them onto a single line, separating each by a comma:

@synthesize forSale, anotherProperty, yetAnotherProperty;

Using this approach creates both the normal setter and getter via dot notation plus the two custom methods, isForSale and setSalable:. Oddly, while you can use dot notation to assign and retrieve forSale, you cannot use the equivalent methods, and you cannot use the customized setter in dot notation. Here is how the usage breaks down:

Car *myCar = [Car car];

// You can use the synthesized setter and getter of course
[myCar setSalable:YES];
printf("The car %s for sale\n",
    myCar.isForSale ? "is" : "is not");

// The normal getter and setter still work in dot notation
myCar.forSale = NO;
printf("The car %s for sale\n",
    myCar.forSale ? "is" : "is not");

// But not the method versions.
// These produce run-time errors
// [myCar setForSale:YES];
// printf("The car %s for sale\n",
//     [myCar forSale] ? "is" : "is not");

// You cannot use the customized setter via dot notation.
// This produces a compile-time error
// myCar.setSalable = YES;

Property Attributes

In addition to read-write and read-only attributes, you can specify whether a property is retained and/or atomic. The default behavior for properties is assign. Assignment acts exactly as if you’d assigned a value to an instance variable. There’s no special retain/release behavior associated with the property, but by making it a property you expose the variable outside the class via dot notation. A property that’s declared

@property NSString *make;

uses the assign behavior.

Setting the property’s attribute to retain does two things. First, it retains the passed object upon assignment. Second, it releases the previous value before a new assignment is made. Using the retain attribute introduces the memory management advantages discussed in the previous section. To create a retained property, add the attribute between parentheses in the declaration:

@property (retain) NSString *make;

A third attribute called copy sends copies the passed object and releases any previous value. Copies are always created with a retain count of 1.

@property (copy) NSString *make;

You can also retain the object as you assign it, as shown here:

myCar.make = @"Ford";
[myCar.make retain];

When you develop in a multithreaded environment, you want to use atomic methods. Xcode synthesizes atomic methods to automatically lock objects before they are accessed or modified and unlock them after. This ensures that setting or retrieving an object’s value is performed fully regardless of concurrent threads. There is no atomic keyword. All methods are synthesized atomically by default. You can, however, state the opposite, allowing Objective-C to create accessors that are nonatomic:

@property (nonatomic, retain) NSString *make;

Marking your properties nonatomic does speed up access, but you might run into problems should two competing threads attempt to modify the same property at once. Atomic properties, with their lock/unlock behavior, ensure that an object update completes from start to finish before that property is released to another read or change.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020