13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 3: Foundational APIs 45The last item in Table 3-1 is interesting: <strong>Objective</strong>-C extends the common C format specifierswith one of its own, %@. This specifier invokes the descriptionWithLocale:method (or thedescription method if descriptionWithLocale: is not available) of an object at runtime. Thismethod, by default, returns a string specifying an object’s type and its location in memory.However, in the case of NSString, the %@ format specifier specifies the text contents of thestring object. Many other classes provide custom description implementations to provide moreinformation about their contents; collection classes and views, for example, return a lot of usefulinformation about the instance’s state.Note The description method is a method that any class may override. While doing so can makedebugging easier, it is usually unwise to include the contents of an object’s description as text tothe user.Listing 3-4 illustrates use of the object format specifier.Listing 3-4. Object Format SpecifiersNSString *aString = @"criminals";NSString *anotherString = [NSString stringWithFormat:@"When you %@ strings, only %@ willuse strings.", @"criminalize", aString];Comparing strings is, as is typical with most languages, not as simple as using the equalityoperator. As with plain C, a function is required to correctly look at the contents of the stringobjects, rather than their addresses. In this case, you use -isEqualToString:, as shown inListing 3-5.Listing 3-5. Correct String ComparisonNSString *aString = @"hello";NSString *anotherString = @"hello";BOOL stringsAreEqual = ([aString isEqualToString:anotherString]);Note In <strong>Objective</strong>-C, the Boolean primitive is represented by the type BOOL which can either be YES orNO (equivalent to true or false, respectively).If you were to use the equality operator alone, you would be comparing the values of two pointervariables, not the character data within the objects they reference. Listing 3-6 would return NO.Listing 3-6. Incorrect String ComparisonNSString *aString = @"hello";NSString *anotherString = @"hello";BOOL stringsAreEqual = (aString == anotherString);Even though the text contents of the string objects are identical, stringsAreEqual is NO. Thisis because using the equality comparison operator compares the values of the pointers to thestring objects; since there are two objects with two distinct pointers, the comparison fails.www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!