The iPhone developer's cookbook (3)

Source: Internet
Author: User
Tags string methods

Briefly introduces the basic classes of OC.

Category
OC's built-in capability to expand already-existing classes is one of its most powerful features. This behavioral expansion is called a category. Categories extend class functionality without subclassing.
Categories add methods to existing classes even if you did not define that class in the first place and do not have the source code for that class.
To build a category, you declare a new interface. Specify the category name (It's arbitrary) within parentheses.
You cannot add new instance variables to a category interface as you cocould when subclassing. You are instead expanding a class's behavior.
Eg:
Building an orientation category for the uidevice class
@ Interface uidevice (orientation)
@ Property (nonatomic, readonly) bool islandscape;
@ End

@ Implementation uidevice (orientation)
-Bool islandscape
{
Return (self. Orientation = uideviceorientationlandscapeleft) |
(Self. Orientation = uideviceorientationlandscaperight );
}
@ End

Protocols
Delegates implement details that cannot be determined when a class is first defined.
Delegation basically provides a language that mediates contact between an object and its handler.

In oC, both delegation and data sourcing are produced by a system called protocols.
Protocols define a priori how one class can communicate with another. they contain a list of methods that are defined outside any class. some of these methods are required. others are optional. any class that implements the required methods is said to conform to the Protocol.

You can use the @ required and @ Optional keywords to declare a protocol to be of one form or the other. any methods listed after an @ required keyword are required; after an @ optional keyword, they are optional.

Nsobject provides a respondstoselector: method, which returns a Boolean yes if the object implements the method or no otherwise.

The majority of protocol methods in the iPhone SDK are optional.

In oC, the core nsstring class is immutable in cocoa. that is, you can use strings to build other strings, but you can't edit the strings Your already own. string constants are delineated by quote marks and the @ character.

Nshomedirectory (), a function that returns a string with a path pointing to the application sandbox.

In cocoa, most file access routines offer an atomic option. when you set the atomically parameter to yes, the iPhone writes the file to a temporary auxiliary and then renames it into place. using an atomic write ensures that the file avoids upload uption.

Using nserror class to store that error information and sends the localizeddescription selector to convert the information into a human-readable form. Whenever iPhone Methods return errors, use this approach to determine which error was generated.

Converting strings to Arrays
You can convert a string into an array by separating its components into SS some repeated boundary.
Nsstring * mystring = @ "One two three four five six seven eight ";
Nsarray * wordarray = [mystring componentsseparatedbystring: @ ""];
Nslog (@ "% @", wordarray );

Requesting indexed substrings
As with standard C, array and string indices start at 0.
Nsstring * sub1 = [mystring substringtoindex: 7];
Nsstring * sub2 = [mystring substringfromindex: 4];

Generating substrings from ranges
Nsange provides a structure that defines a section within a series. You use ranges with indexed items like strings and arrays.
Nsange R;
R. Location = 4;
R. Length = 2;
Nsstring * sub3 = [mystring substringwithrange: R];

Search and replace with strings
Nsange searchrange = [mystring rangeofstring: @ "five"];
If (searchrange. location! = Nsnotfound)
Nslog (@ "range location: % d, Length: % d", searchrange. Location, searchrange. Length];
Searches return range, which contain both a location and a length. Once you 've found a range, you can replace A subrange with a new string.
Nslog (@ "% @", [mystring stringbyreplacingcharactersinrange: searchrange withstring: @ "New String"]);

A more general approach lets you replace all occurrences of a given string.
Mystring = @ "One * Two * Three * Four * Five * Six ";
Nsstring * replace = [mystring stringbyreplacingoccurrencesofstring: @ "" withstring: @ "*"];

Changing case
Nsstring * mystring = @ "Hello world. How do you do? ";
Nslog (@ "% @", [mystring uppercasestring]);
Nslog (@ "% @", [mystring lowercasestring]);
Nslog (@ "% @", [mystring capitalizedstring]);

Extracting numbers from strings
Nsstring * S1 = @" 3.141592 ";
Nslog (@ "% d", [S1 intvalue]);
Nslog (@ "% d", [S1 boolvalue]);
Nslog (@ "% F", [S1 floatvalue]);
Nslog (@ "% F", [S1 doublevalue]);

Mutable strings
The nsmutablestring class is a subclass of nsstring. it offers you a way to work with strings whose contents can be modified. once instantiated, You can append new contents to the string, allowing you to grow results before returning from a method.
Nsmutablestring * mymstring = [nsmutablestring stringwithstring: @ "Hello world."];
[Mymstring appendformat: @ "The results are % @ now.", @ "in"];
Nslog (@ "% @", mymstring );

Nsnumber class lets you treat numbers as objects.
One of the biggest reasons for using nsnumber objects rather than ints, floats, and so forth, is that you can use them with cocoa routines and classes.

The nsdecimalnumber class provides a handy object-oriented wrapper for base-10 arithmetic.

Nsdate objects use the number of seconds since an epoch, that is a standardized universal time reference, to represent the current date. the iPhone epoch was at midnight on January 1, 2001. the standard UNIX epoch took place at midnight on January 1, 1970.

Each nstimeinterval represents a span of time in seconds, stored with subsecond floating-point precision.
// Current time
Nsdate * Date = [nsdate date];

// Time 10 seconds from now
Date = [nsdate datewithtimeintervalsincenow: 10.0f];

You can compare dates by setting or checking the time interval between them.
// Sleep 5 seconds and check the time interval
[Nsthread sleepuntildate: [nsdate datewithtimeintervalsincenow: 5.0f];
Nslog (@ "slept % F seconds", [[nsdate date] timeintervalsincedate: DATE]);
// Show the date
Nslog (@ "% @", [date description]);

Nsdateformatter class.
// Produce a formatted string representing the current date
Nsdateformatter * formatter = [[nsdateformatter alloc] init] autorelease];
Formatter. dateformat = @ "mm/DD/yy hh: mm: SS ";
Nsstring * timestamp = [formatter stringfromdate: [nsdate date];
Nslog (@ "% @", timestamp];

Timer class
To disable a timer, send it the invalidate message; this release the timer object and removes it from the current runloop;
[Timer invalidate];

Recovering information from index paths
The nsindexpath class is used with iPhone tables. It stores the section and row number for a user selection, that is, when a user taps on the table.

Collections
The iPhone primarily uses three kinds of collections: arrays, dictionaries, and sets.
Create Arrays Using the arraywithobjects: convenience method, which returns an autorelease array. when calling this method, list any objects you want added to the array and finish the list with nil. (If you do not include nil in your list, you'll experience a runtime crash .)
Nsarray * array = [nsarray arraywithobjects: @ "one", @ "two", @ "three", nil];
Arrays are indexed starting with 0, up to one less than the count. Attempting to access [array objectatindex: array. Count] causes an "index beyond bounds" exception and crashes.

The mutable form of nsarray is nsmutablearray. With mutable arrays, you can add and remove objects at will.

Checking Arrays
If ([marray containsobject: @ "four"])
Nslog (@ "the index is % d", [marray indexofobject: @ "four"]);

Converting arrays into strings
Nsarray * array = [nsarray arraywithobjects: @ "one", @ "two", @ "three", nil];
Nslog (@ "% @", [array componentsjoinedbystring: @ ""];

Nsdictionary class and nsmutabledictionary class.
Creating dictionaries
Nsmutabledictionary * dict = [nsmutabledictionary dictionary];
[Dict setobject: @ "1" forkey: @ "A"];
[Dict setobject: @ "2" forkey: @ "B"];
[Dict setobject: @ "1" forkey: @ "C"];
Nslog (@ "% @", [dict description]);

Searching dictionaries
Nslog (@ "% @", [dict objectforkey: @ "A"]; // return @ "1"
Nslog (@ "% @", [dict objectforkey: @ "F"]; // return Nil

When you set a new object for the same key, cocoa replaces the original object in the dictionary.

Removing objects
[Dict removeobjectforkey: @ "B"];
Once removed, both the key and the object no longer appear in the dictionary.

Listing keys
Nslog (@ "The dictionary has % d object", [dict count]);
Nslog (@ "% @", [dict allkeys]);

Arrays, sets and dictionaries automatically retain objects when they are added and release those objects when they are removed from the collection. releases are also sent when the collection is deallocated. collections do not copy objects. instead, they rely on retain counts to hold onto objects and use them as needed.

Both arrays and dictionaries can store themselves into files using writetofile: atomically: methods so long as the types within the collections belong to the set of nsdata, nsdate, nsnumber, nsstring, nsarray, and nsdictionary.
Nsstring * Path = [nshomedirectory () stringbyappendingpathcomponent: @ "events/arraysample.txt"];
If ([array writetofile: path atomically: Yes])
Nslog (@ "file was written successfully ");

To recover an array or dictionary from file, use the convenience Methods arraywithcontentsoffile: And dictionarywithcontentsoffile:. If the methods return nil, the file cocould not be read.
Nsarray * array = [nsarray arraywithcontentsoffile: path];
Nslog (@ "% @", newarray );

Building URLs
Nsurl objects point to resources. These resources can refer to both local files and to URLs on the web.
Nsstring * Path = [nshomedirectory () stringbyappendingpathcomponent: @ "Documents/foo.txt"];
Nsurl * url1 = [nsurl fileurlwithpath: path];
Nslog (@ "% @", url1];

Nsstring * urlpath = @ "http://ericasadun.com ";
Nsurl * url2 = [nsurl urlwithstring: urlpath];
Nslog (@ "% d characters read", [[nsstring stringwithcontentsofurl: url2] length]);

Nsdata provides data objects that store and manage bytes. Often you fill nsdata with the contents of a file or URL. The data returned can report its length, leader you know how many bytes were retrieved.
Nsdata * Data = [nsdata datawithcontentsofurl: url2];
Nslog (@ "% d", [Data Length]);

To access the core byte buffer that underlies an nsdata object, use bytes. This returns a (const void *) pointer to actual data.
Nsmutabledata. You can keep growing mutable data by issuing appenddata: to add the new information as it is already ed.

File Management
The iPhone's file manager is a singleton provided by the nsfilemanager class. It can list the contents of folders to determine what files are found and perform basic file system tasks.

OC does not provide true multiple-inheritance, it offers a workaround that lets objects respond to message that are implemented in other classes. if you want your object to respond to another class's messages, you can add message forwarding to your applications and gain access to that object's methods.

Normally, sending an unrecognized message produces a runtime error, causing an application to crash. but before the crash happens, the iPhone's runtime system gives each object a second chance to handle a message. catching that message lets you redirect it to an object that understands and can respond to that message.

OC provides this functionality through a process called message forwarding.
when you send a message to an object that cannot handle that selector, the selector gets forwarded to a forwardinvocation: method. the object send with this message, namely an nsinvocation instance stares the original selector and arguments that were requested. you can override forwardinvocation: and send that message on to another object.

Implementing message forwarding
To add message forwarding to your program, you must override two methods, namely, methodsignatureforselector: And forwardinvocation :. the former creates a valid method signature for messages implemented by another class. the latter forwards the selector to an object that actually implements that message.
The first method returns a method signature for the requested selector.
The second method you need to override is forwardinvocation :. this method only gets called when an object has been unable to handle a message. this method gives the object a second change, allowing it to redirect that message. the method checks to see whether the message (self. carinfo) string responds to the selector.

Using forwarded messages
Calling nonclass messages like utf8string and length produces compile-time warnings, which you can ignore.

Although invocation forwarding minics multiple inheritance, nsobject never confuses the two. Methods like respondstoselector: And iskindofclass: only look at the inheritance hierarchy and not at the forwarding change.

Reimplementing respondstoselector: And iskindofclass: Lets other class query your class. in return, the class announces that it responds to all string methods (in addition to its own) and that it is a "kind of" string, further emphasizing the pseudo-multiple inheritance approach.

Supereasy forwarding

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.