head first iphone development a learners guide to creating objective c applications for the iphone 3 phần 3 potx

54 463 0
head first iphone development a learners guide to creating objective c applications for the iphone 3 phần 3 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

iPhone app patterns .and then add the implementation #import “InstatwitViewController.h” @implementation InstatwitViewController @synthesize tweetPicker; along with the @ synthesize goes tion in the h @property decla for more info pter file See Cha - (void)dealloc { [tweetPicker release]; [activities release]; [feelings release]; InstatwitViewController.m The last thing you need to wit tweetPicker is release our refere h another memory thing We’ll com nce to it memory management in Chapter e back to the 3, we promise [super dealloc]; } @end What’s next? you are here 4   77 connect the outlet to the code Connect the picker to our outlet You’re probably expecting this by now! Back into Interface Builder to make the connection from the UIPickerView to the IBOutlet in our view controller Right-click on the UIPickerView, grab the circle next to the “New Referencing Outlet,” and drop it on File’s Owner—our InstatwitViewController sporting its new tweetPicker outlet When you click and drag up eto to File’s Owner, you will be ablker tweetPic connect it to the outlet you just created What you need to now to get the data out of the picker and into your Twitter message? Think about the “Tweet it!” button press action and how that will need to change 78   Chapter iPhone app patterns Use our picker reference to pull the selected values Now all that’s left is to use our reference to the picker to get the actual values Mike selects We need to reimplement the sendButtonTapped method to pull the values from the picker Looking at the UIPickerView documentation, the method we need is selectedRowInComponent: That method returns a row value, which, just like before, we can use as an index into our arrays our callback We ementation for ill in the values from Here’s the imple a string and f t need to creat he “%@” in the string format ge the picker t the values we pass in replaced with To figure out wha picker, we need tot Mike chose on the is selected, and ask the picker what row from our arrays get the corresponding string - (IBAction) sendButtonTapped: (id) sender { NSString* themessage = [NSString stringWithFormat:@”I’m %@ and feeling %@ about it.”, [activities objectAtIndex:[tweetPicker selectedRowInComponent:0]], [feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]]]; NSLog(themessage); NSLog(@”Tweet button tapped!”); } Pull this log message out and put in one to see what the final Twitter message will be full tweet text string with the ormat method to ild a new We want to buuse NSString’s stringWithF of other options in it, so we’ll ated string There are lots acters, integers, create a templ ith a string format, like char two selected you could use w w we just need to insert the etc., but for no use %@ strings, so we’ll InstatwitViewController.m We’re just going to log this message to the console so we can see the string we’re building, and then we’ll send this to Twitter in just a minute Let’s make sure we implemented this correctly first before tweeting to the whole world you are here 4   79 ready to tweet Test Drive OK, try it out You should get a convincing tweet in the console: is ter info, this add the Twitw up in your feed Once we lly sho what will actua as a tweet All that’s left is to talk to Twitter— we’ll help you with that 80   Chapter iPhone app patterns Ready Bake Code To post to Twitter, we’re going to use their API Rather than go into a Twitter API tutorial, we’ll give you the code you need to tweet the string Type the code you see below into the InstatwitViewController.m, just below the NSLog with the Twitter message in the sendButtonTapped method //TWITTER BLACK MAGIC Your username and password need to go in here NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@”http://YOUR_TWITTER_USERNAME:YOUR_TWITTER_PASSWORD@twitter.com/ statuses/update.xml”] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [theRequest setHTTPMethod:@”POST”]; [theRequest setHTTPBody:[[NSString stringWithFormat:@”status=%@”, themessage] dataUsingEncoding:NSASCIIStringEncoding]]; NSURLResponse* response; NSError* error; NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error]; NSLog(@”%@”, [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]); // END TWITTER BLACK MAGIC InstatwitViewController.m  you don’t have a Twitter account, If just go get one! Just go to twitter.com and register Once you that, you can enter your username and password, and this will work like a charm After adding that code, you can just save, build and go It will now show up on your Twitter feed Go ahead, try it out! you are here 4   81 mike’s feeling great about your app That is great! Now, Renee is happy and feels included and I don’t actually have to talk out loud about my feelings At all Ever 82   Chapter iPhone app patterns iPhonecross Puzzle Untitled Header Info Header Info etc Flex your vocab skills with this crossword 10 11 Across This typically handles the information itself in the app This is the document Apple uses to evaluate apps for the App Store You see this listed in the view and it controls the view This component allows for controlled input from several selections 10 This type of app is typically one screen, and gives you the basics with minimal interaction 11 These define to which messages the datasource and delegate respond Down This typically contains the logic that controls the flow of information in an app The best way to figure out what protocols you need to worry about is to check the This app type typically involves hierarchical data This app type is mostly custom controllers and graphics The other name for an *.xib file you are here 4   83 more app types We’ve listed a couple of descriptions of a some different apps Using the app description, sketch out a rough view and answer the questions about each one Generic giant button app There are several of these currently up for sale on the app store This app consists of pushing a big button and getting some noise out of your iPhone What type of app is this? What are the main concerns in the HIG about this app type? Book inventory app This app’s mission is to keep a list of the books in your library, along with a quick blurb of what it’s about and the author What type of app is this? What are the main concerns in the HIG about this app type? 84   Chapter iPhone app patterns iPhonecross Solution Untitled Puzzle Header Info Header Info etc Flex your vocab skills with this crossword H A T A S O U R C U M A N I N T E R F A C E M F I L E T I R C O U G U I D E M O W N E R I T T C N T T I A F V T I I N L E B S U P S U O A R 10 P E I E D L D D Y V E I C K E R I 11 L P E R O T Y O C O L S N Across Down This typically handles the information itself in the app [DATASOURCE] This is the document apple uses to evaluate apps for the App Store [HUMANINTERFACEGUIDE] You see this listed in the view and it controls the view [FILESOWNER] This component allows for controlled input from several selections [PICKER] 10 This type of app is typically one screen, and gives you the basics with minimal interaction [UTILITY] 11 These define to which messages the datasource and delegate respond [PROTOCOLS] This typically contains the logic that controls the flow of information in an app [DELEGATE] The best way to figure out what protocols you need to worry about is to check the [DOCUMENTATION] This app type typically involves hierarchical data [PRODUCTIVITY] This app type is mostly custom controllers and graphics [IMMERSIVE] The other name for an *.xib file [NIBFILE] you are here 4   85 exercise solution We’ve listed a couple of descriptions of a some different apps Using the app description, sketch out a rough view and answer the questions about each one Generic giant button app There are several of these currently up for sale on the app store This app consists of pushing a big button and getting some noise out of your iPhone Bug button that you push What type of app is this? An immersive app What are the main concerns in the HIG about this app type? The big thing Apple cares about is that controls “provide an internally consistent experience.” So everything can be custom, it needs to focused and well organized Book inventory app This app’s mission is to keep a list of the books in your library, along with a quick blurb of what it’s about and the author What type of app is this? A productivity app Just one view Some navigation stuff here Book list What are the main concerns in the HIG about this app type? The HIG has many more specific rules about this app type, because you’ll be using standard controls EACH control needs to be checked out for proper usage Another view for details, need to figure out how to get to it 86   Chapter messages up close Handling Messages Up Close You’ve been handling messages since Chapter 1, but we really haven’t talked about the syntax to make it work Method declarations go in your header files and the implementation goes in the m Here are some snippets from our sendButtonTapped implementation from InstaTwit Implementation files implementation, then (.m) start with @ class you’re implemen the name of the ting @implementation InstatwitViewController se You specify the responfore nthesis be type in pare the message names - the Next is the name of ssage name e full me message Th da (with arguments) is calle nds to te selector in Obj-C ande d descriptiv be long an (IBAction)sendButtonTapped: (id) sender { New method code here } The “-” means it method (whereas ’s an instance a static or class a “+” means method) @end If there are arguments to message, follow the messageyour with a colon, then the type name and name of the local variable Additional arguments get names, types, and variable names, too mentation of the Finally, provide the impleinterface method declared in our ge The syntax for declaring a messa the as in in a header file is the same implementation file Implementation files all end with @end InstatwitViewController.m 116   Chapter objective-c for the iPhone Messages in Objective-C use named arguments In Objective-C, message names tend to be long and descriptive This really starts to make sense when you see arguments tacked on When you send a message with arguments, the message and argument names are all specified Objective-C messages read more like sentences Let’s look at a method declaration from UIPickerViewDataSource This method returns the number of rows for a given component in a picker view It’s declared like this: Return type First argument type Method name Local argument name Public name of t second argumen - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfR owsInComponent:(NSInteger)component; Local name of second argument Type of second argument Methods can have internal and external names for arguments; the external name is used when sending the message to the receiver So when iPhoneOS wants to send this message to our delegate, it creates a call like this: Receiver value Message name Second argument name Second argument value [pickerDelegate pickerView:somePicker numberOfRowsInComponent:component]; Q: You keep switching terms back and forth between methods and messages Which is it? A: Both are correct, depending on your context 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 Q: friendly public name for people when they use your class and a convenient local name in your code A: One more interesting fact: the public name is optional If you don’t provide one, people just use a colon and the argument value when sending the message to your object Obviously, the argument order is critical So about those arguments to methods what’s the deal with the name before the colon and the one after the type? 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 More on selectors in a minute you are here 4   117 message to controller Use message passing to tell our view controller when the Done button is pressed Messages going here between UITextField and the controller The text field can tell our ViewController when the Done button was pressed on the keyboard; we just need to tell it what message to send We can this with Interface Builder You’ll need to declare an action in both the h and and implement it in the m file: Add the IBAction to InstatwitViewController.h Just like we did with the “Tweet it” button, go back into Xcode and add this: - (IBAction) sendButtonTapped: (id) sender; - (IBAction) textFieldDoneEditing:(id) sender; Notice how @end is in parenththe IBAction the response esis? That’s which is secr type #defined to etly just void e ‘-’ says it’s an Here’s the new action.dTh xtFieldDoneEditing, te instance method, callent The sender is of type e argume and takes on er to something) ‘id’ (which means a point The signat r method (vouide for this and one argu return type ‘id’) is requir ment of type ed for IB actions InstatwitViewController.h Add the method implementation in InstatwitViewController.m Now that we have an action that will be called when the Done button is pressed, we just need to ask the textField to resign its first responder status and it will hide the keyboard // Since the sender is the UITextField, we can send the resignFirstResponder right back to it END TWITTER BLACK MAGIC } - (IBAction)textFieldDoneEditing:(id) sender { gument will The sender arnent that be the compo event In triggered the ill be the our case, it w UITextField [sender resignFirstResponder]; } InstatwitViewController.m Almost there, we just need to wire it up 118   Chapter objective-c for the iPhone Connect the UITextField event in Interface Builder Now the actions are declared, go back into Interface Builder by double clicking on InstatwitViewController.xib If you right-click on the UITextField you’ll bring up the connections In the list of events that the UITextField can send, choose the “Did End on Exit” event and connect it to the File’s Owner’s “textFieldDoneEditing” action we just created Geek Bits The UITextField has a number of events that it can raise, just like the round rectangular button Take a second and check out the list that’s there Along with the customizing that you can in the Inspector with the field, you can wire up different (or even multiple!) responses to interaction with the field Keep it in mind for your own apps you are here 4   119 no dumb questions Q: Why did we send the message back to the sender in our action and not to our notesField property? A: Either one would work fine; they’re both references to the same object We used the sender argument because it would work regardless of whether we had a property that was a reference to our UITextField Q: You mentioned selectors, but I’m still fuzzy on what they are 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, the code on page 66 is using the selector pickerView:numberO fRowsInComponent You’ll see them show up again in later chapters when we more interface connecting in code For now, Interface Builder is handling it for us Q: When we send the resignFirstResponder message to sender, the sender type is “id” How does that work? 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: What happens if an object can’t respond to a message? A: You’ll get an exception This is the reason you should use strongly typed variables whenever possible 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: So seriously, brackets for message passing? A: Yes And indexing arrays We all just have to deal with it ƒƒ In Objective-C you send messages to receivers The runtime maps these to method calls ƒƒ Method arguments are usually named, and those names are used when sending a message ƒƒ Method declarations go in the header (.h) file after the closing brace of an interface ƒƒ Arguments can have an internal and external name ƒƒ Method implementations go in the implementation (.m) file between the @implementation and the @ end 120   Chapter ƒƒ Use a “-” to indicate an instance method; use “+” to indicate a static method objective-c for the iPhone Test Drive Do some typing, go ahead! It works! The keyboard goes away and you can play around with the text field and add some notes now If you have your account info in the code, remember every time tweet it actually will! you Tap the “done” button you are here 4   121 custom note is missing Something’s still not right Mike’s ready to try out the custom field and see what happens, but when he puts in his custom message Mike sends a tweet No custom info at all The custom note doesn’t anything! It’s not showing up on Twitter 122   Chapter You can fix this with no problem now that you’ve gotten the hang of events and message passing objective-c for the iPhone BE the architect Your job is to be architect and figure out how the UITextField and the Tweet button need to work together using the View View Controller model View View Controller you are here 4   123 build the tweet BE the architect solution Your job is to be architect and figure out how the UITextField and the Tweet button need to work together using the View View Controller model Show typed text View Communicate button push Respond to button-tapped message View Controller Get the text from the view Update the datasource with the text Build the tweet with strings We need to incorporate the note text into our tweet In order to that, we’re going to a little string manipulation with the core string classes You’ve already built a message to send to Twitter, but this time we have more text to include Before you refactor the code to send the tweet with the new text in it, let’s take a closer look at what you did in Chapter 2: The SString This string didn’t come from allo new, copy, or mutableCopy, so it’lc, l be autoreleased @ be ethod on N means thisfore the quotes a static ming format and should be This is es a str rs with t e that tak he format placeholduements nort ated as an NSStrin g, a char* replaces t you provide as arg lues the va NSString* themessage = [NSString stringWithFormat:@”I’m %@ and feeling %@ about it.”, [activities objectAtIndex:[tweetPicker selectedRowInComponent:0]], [feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]]]; NSLog(themessage); String you pass NSLog prints out whatever NS your app won’t it to the console End users of see these message eate ithFormat to cr e use the stringWe the %@, which is a Here w Not our message string string a placeholder for Now all you need to update this to include the text from the Notes field Take a look at the magnets on the next page and get it working 124   Chapter objective-c for the iPhone Xcode Magnets You need to modify InstatwitViewController.m file to add the custom field to the message Using the information you just learned and the magnets below, fill in the missing code - (IBAction) sendButtonTapped: (id) sender { NSString* themessage = [NSString stringWithFormat:@” I’m %@ and feeling %@ about it.”, [activities objectAtIndex:[tweetPicker selectedRowInComponent:0]], [feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]]]; NSLog(themessage); init]; [[NSString alloc] , notesField.text :@”” %@ [themessage release]; tResponder sender resignFirs themessage ? notesField.text notesField.text you are here 4   125 magnets solution Xcode Magnets Solution You need to modify InstatwitViewController.m file to add the custom field to the message Using the information you just learned and the magnets below, fill in the missing code Here’s our new stri for the notes textng placeholder InstatwitViewController.m - (IBAction) sendButtonTapped: (id) sender { %@ NSString* themessage = [NSString stringWithFormat:@” I’m %@ and feeling %@ about it.”, notesField.text notesField.text ? :@”” , [activities objectAtIndex:[tweetPicker selectedRowInComponent:0]], [feelings objectAtIndex:[tweetPicker selectedRowInComponent:1]]]; NSLog(themessage); g pty strin nd an emtring, so e nil, we’ll s NSS nd if it ,isit has to be an quotes .a r Remembe he @ before the t we put We have to handle text If the text the case where the user didn’t en Here we use the C field is empty, its text property ter any isn’t nil, it will use style ternary operator If notesFwill be nil ield.text the value in notesF ield.text just like in The ? is a ternary operator,expression Java or C++, where if the value, is true it returns the first ond otherwise, it returns the sec init]; [[NSString alloc] [themessage release]; themessage tResponder sender resignFirs 126   Chapter notesField.text objective-c for the iPhone Test Drive Go ahead and build and run the app with the new text code in it Now it has custom text! w00t! It’s so great that we can talk about our feelings you are here 4   127 objective-ccross Objective-Ccross Practice some of your new Objective-C terminology Untitled Puzzle Header Info Header Info etc 10 Across Down The control with focus has _ status This incorporates another file Unique names for methods after Objective-C translation are _ Signals that the compiler will retain the object Automatic methods 10 This tells the compiler to skip mutexes An array of objects that will be released after the current event A "+" before a method declaration indicates that it's a This is sent between objects _ management is important for iPhone apps 128   Chapter objective-c for iPhone Your Objective-C Toolbox CHAPTER You’ve got Chapter under your belt and now you’ve added Objective-C to your toolbox For a complete list of tooltips in the book, go to http://www.headfirstlabs.com/ iphonedev Attribute You want it readwrite 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 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 When you’re dealing with basic types, like ints, floats, etc The compiler just creates a setter with a simple myField = value statement This is the default, but not usually what you want When you’re dealing with object values The compiler will retain the value you pass in (we’ll talk more about retaining in a minute) and release the old value when a new one comes in 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 retains that readonly assign retain copy C Objectivgeag-of iPhone apps u e n - Is the la ed language ject orient - Is an ob nagement memory ma nced - Has adva dynamic passing and sage - Uses mes typing terfaces ance and in it - Has inher Memory Management - You must release objects you create with alloc, new, copy or mutableCopy - Everything else needs to have a retain count of and in the autorelease pool you are here 4   129 objective-ccross solution Objective-Ccross Solution Untitled Puzzle Header Info Header Info etc Practice some of your new Objective-C terminology A U F I R S S T R E S P A I M P O R O T P R O P E A R T I E O N A T M R E S S M E L E C T O A R S R G R Y E T A I N S E H N E E T 10 D L M @ N E C M R I T P O M D I C O O L Across Down The control with focus has _ status [FIRSTRESPONDER] This incorporates another file [IMPORT] Unique names for methods after Objective-C translation are _ [SELECTORS] Signals that the compiler will retain the object [RETAIN] Automatic methods [@PROPERTIES] 10 This tells the compiler to skip mutexes [NONATOMIC] An array of objects that will be released after the current event [AUTORELEASEPOOL] A "+" before a method declaration indicates that it's a [STATICMETHOD] This is sent between objects [MESSAGE] _ management is important for iPhone apps [MEMORY] 130   Chapter ... block of code: from the alloc, from inserting it into the array Arrays automatically retain items added to them 1 This still has a retain count of because of the alloc, but is now in the autorelease... memory as they in C, but use alloc to instantiate classes Q: What’s with that init call that you always put after the alloc? A: Objective- C doesn’t have constructors like other Object Oriented languages... argument order is critical So about those arguments to methods what’s the deal with the name before the colon and the one after the type? In Objective- C you can have a public name and a local

Ngày đăng: 14/08/2014, 20:21

Từ khóa liên quan

Mục lục

  • 2. iPhone app patterns: Hello @twitter!

    • Connect the picker to our outlet

    • Use our picker reference to pull the selected values

    • iPhonecross

    • iPhonecross Solution

    • Your iPhone Toolbox

    • 3. objective-c for the iPhone: Twitter needs variety

      • Renee is catching on....

      • Make room for custom input

      • Header files describe the interface to your class

      • Auto-generated accessors also handle memory management

      • Objective-C can automatically release references, too.

      • To keep your memory straight, you need to remember just two things

      • But when Mike’s finished typing...

      • Customize your UITextField

        • Next change the label on the return key

        • Components that use the keyboard ask it to appear...

          • ...by passing messages to other objects

          • Ask the textField to give up focus

          • Messages in Objective-C use named arguments

          • Use message passing to tell our viewcontroller when the Done button is pressed

          • Something’s still not right

          • Build the tweet with strings

          • Objective-Ccross

Tài liệu cùng người dùng

Tài liệu liên quan