Interlude: Syntax - Head First iPhone and iPad Development (2013)

Head First iPhone and iPad Development (2013)

Chapter 3. Interlude: Syntax

image with no caption

It’s time to get into some details. You’ve written a couple apps and gotten some of the big picture stuff sorted out. Now it’s time to get into some line by line details. Why are there @ symbols everywhere? What’s the difference between a method and a message? What exactly do properties do? It’s time to take a quick dive into the syntax of Objective-C; then we can get back into building apps.

Classes: Interface and Implementation

In Objective-C, a class is split into separate files, the .h and .m files. The .h file defines how other objects should interact with your class. It defines the properties, methods, and other attributes.

The .m file, which imports the .h, implements the internal behavior of your class. The compiler will check to make sure what is defined in your interface file has an implementation in the .m.

image with no caption

Header files describe the interface to your class

In Objective-C, classes are defined with interfaces in the header file. It’s where you declare whether your class inherits from anything, as well as your class’s instance variables, properties, and methods.

As Objective-C matured, more code has been moved into the implementation file as a class extension. This is the only way to define truly “private” properties and methods.

image with no caption

SHARPEN YOUR PENCIL

Here’s our ViewController.h file from MarcoPollo. Fill in the blanks and explain what each line does.

________________________ #import <UIKit/UIKit.h>

________________________ @interface ViewController : UIViewController

________________________ @property (weak, nonatomic) IBOutlet

UITextView *tweetTextView;

________________________ - (IBAction)postItButtonPressed:(id)sender;

________________________ @end

image with no caption

SHARPEN YOUR PENCIL SOLUTION

Here’s our current ViewController.h file. Let’s see how you explained what each line does.

image with no caption

SHARPEN YOUR PENCIL SOLUTION

image with no caption

Properties are about efficiency

To work with an object, properties allow you to create the setter and getter methods; they also provide some other help. By putting creation of those methods on the compiler, it can also check to make sure that all your properties are used and to handle synthesizing the accessor methods. All for one line of code.

image with no caption

Property attributes talk to the compiler

To dictate exactly how the accessor methods work, you declare attributes of the property. They are broken into three categories: write-ability, setter semantics, and atomicity. Properties are atomic by default. This means that those accessor methods that are synthesized always return or set a value in a mulithreaded environment.

If you dive into the list of attributes in the Apple Developer documentation, you can see the complete list.

image with no caption

That’s right! Properties protect your variables.

By defining a property, we restrict the way other objects interact with our class’s data. This promotes good encapsulation and ensures our class manages how we manage the data.

WHO DOES WHAT?

Below is a list of the most commonly used property attributes and definitions. Match each attribute with its definition.

read-only

When you want the property to be modifiable by people. The compiler will generate a getter and a setter for you. This is the default.

strong

This attribute does not keep the referenced object alive. It’s set to nil when there are no strong references to the object. With this reference, you don’t take ownership of the object..

read/write

When you’re dealing with object values. The object remains “alive” as long as there is a strong pointer to it. With this reference, you claim ownership to the object.

copy

When you don’t want people modifying the property. You can still change the field value backing the property, but the compiler won’t generate a setter.

weak

When you want to hold onto a copy of some value instead of the value itself; for example, if you want to hold onto an array and don’t want people to be able to change its contents after they set it. This sends a copy message to the value passed in, then keeps that.

WHO DOES WHAT? SOLUTION

Below is a list of the most commonly used property attributes and definitions. Match each attribute with its definition.

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: How does the compiler know what field to use to hold the property value?

A:

A: When a property is automatically synthesized for you, an ivar is automatically generated for you by the compiler. This ivar is named the same as the property with a preceding _. For example, a property named superSecretField will have a backing ivar named _superSecretField. You can change this by adding a custom @synthesize, but we suggest sticking with best practices.

Q:

Q: What about that nonatomic keyword?

A:

A: By default, generated accessors are multithread safe and use mutexes when changing a property value. These are considered atomic. However, if your class isn’t being used by multiple threads, that’s a waste. You can tell the compiler to skip the whole mutex thing by declaring your property as nonatomic. Note that just making your properties atomic doesn’t mean your whole class is thread safe, so be careful here.

Message passing: How Objective-C gets around

When you want to interact with another object in Objective-C, you pass it a message. The message may or may not include arguments, and the combination of the method name and arguments is called the selector. Remember, messages are sent to another object, where it’s handled by amethod implementation.

Below is a message used with the UIPickerView controller (we used it in InstaTwit; it’s the controller that spins like a dial). This method returns the number of rows for a given component in a picker view. It’s declared like this:

image with no caption

OBJECTIVE-C MAGNETS

This is a message from the Marco Pollo ViewController.m file; it tells this composer view to set the initial text. Build the message itself and then add the description of the pieces of the message too.

image with no caption

OBJECTIVE-C MAGNETS SOLUTION

Here’s how you built the message from the MarcoPollo ViewController.m file; it tells this composer view to set the initial text. Build the message itself and then add the description of the pieces of the message too.

image with no caption

THERE ARE NO DUMB QUESTIONS

Q:

Q: So about those arguments to methods...what’s the deal with the name before the colon and the one after the type?

A:

A: In Objective-C, you can have a public name and a local name for arguments. The public name becomes part of the selector when someone wants to send that message to your object. That’s the name before the colon. The name after the type is the local variable; this is the name of the variable that holds the value. In Objective-C, they don’t have to be the same, so you can use a nice friendly public name for people when they use your class and a convenient local name in your code.

Q:

Q: You mentioned selectors, but I’m still fuzzy on what they are.

A:

A: Selectors are unique names for methods when Objective-C translates a message into an actual method call. It’s basically the method name and the names of the arguments separated by colons. For instance, look at the code using the selector pickerView:numberOfRowsInComponent. You’ll see them show up again in later chapters when we do more interface connecting in code. For now, Interface Builder is handling it for us.

Q:

Q: When we send the resignFirstResponder message to sender, the sender type is “id”. How does that work?

A:

A: “id” is an Objective-C type that can point to any Objective-C object. It’s like a void* in C++. Since Objective-C is a dynamically typed language, it’s perfectly OK with sending messages to an object of type “id”. It will figure out at runtime whether or not the object can actually respond to the message.

Q:

Q: What happens if an object can’t respond to a message?

A:

A: You’ll get an exception. This is the reason you should use strongly typed variables whenever possible—it will generate warnings at compile time, not just runtime problems. However, there are times when generic typing makes a lot of sense, such as callback methods when the sender could be any number of different objects.

Q:

Q: So seriously, brackets for message passing?

A:

A: Yes. And indexing arrays. We all just have to deal with it.

image with no caption

A message is a request for a particular named method with particular arguments. In Objective-C, you send messages to objects and they respond.

The Objective-C runtime turns your message into a method call, which returns a value. So, generally you talk about sending some receiver a message, but if you’re implementing what it does in response, you’re implementing a method.

Objective-C tries to match your message to an existing method... and it might not be successful!

image with no caption

RELAX

You don’t have to get it all now. This is pretty deep...it will all get easier!

We’re down in the weeds now trying to make the semicolons and actual text make more sense. We’re getting ready to dive into another app and give it some context...

image with no caption

Messages let you define message receivers at runtime, not just compile time.

Sending a message is the way objects interact with each other. It’s how you instruct an object to perform a task or compute a value. Even accessing a property is turned into a message by the compiler.

Apple’s documentation uses the message terminology throughout.

BULLET POINTS

§ In Objective-C, you send messages to receivers. The runtime maps these to method calls.

§ Method declarations go in the header (.h) file after the closing brace of an interface.

§ Method implementations go in the implementation (.m) file between the @implementation and the @end.

§ Method arguments are usually named, and those names are used when sending a message.

§ Arguments can have an internal and external name.

§ Use a “-” to indicate an instance method; use “+” to indicate a static method.

Speaking of messages....

image with no caption

It’s time to get back to work...

SYNTAX CROSS

Let's make sure you learned your terms! It makes reading Apple documentation way easier.

image with no caption

Across

Down

8. In Objective-C, a _______ is made up of a .h and a .m file.

9. You send messages to _______.

11. This incorporates another file.

12. Signals that the compiler will retain the object.

1. This tells the compiler to skip mutexes.

2. Automatic methods

3. Unique names for methods after Objective-C translation are _________.

4. Arguments can have an _______ and external name.

5. This property creates a setter for the basic types.

6. _________ management is important for iPhone apps.

7. This is sent between objects.

10. Objective-C tries to match your message to an existing _________.

Your Syntax toolbox

You’ve got Chapter 3 under your belt and now you’ve added some syntax to your toolbox.

image with no caption

BULLET PONINTS

§ In Objective-C, you send messages to receivers. The runtime maps these to method calls.

§ Method declarations go in the header (.h) file after the closing brace of an interface.

§ Method implementations go in the implementation (.m) file between the @implementation and the @end.

§ Method arguments are usually named, and those names are used when sending a message.

§ Arguments can have an internal and external name.

§ Use a “-” to indicate an instance method; use “+” to indicate a static method.

SYNTAX CROSS SOLUTION

Let's make sure you learned your terms! It makes reading Apple documentation way easier.

image with no caption

Across

Down

8. In Objective-C, a _______ is made up of a .h and a .m file. [CLASS]

9. You send messages to _______. [RECEIVERS]

11. This incorporates another file. [IMPORT]

12. Signals that the compiler will retain the object. [RETAIN]

1. This tells the compiler to skip mutexes. [NONATOMIC]

2. Automatic methods [@PROPERTIES]

3. Unique names for methods after Objective-C translation are _________. [SELECTORS]

4. Arguments can have an _______ and external name. [INTERNAL]

5. This property creates a setter for the basic types. [ASSIGN]

6. _________ management is important for iPhone apps. [MEMORY]

7. This is sent between objects. [MESSAGE]

10. Objective-C tries to match your message to an existing _________. [METHOD]