Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Beginning with basics of iOS


Published on

The iOS – previously known as iPhone OS is an Operating System of Apple Inc. for all its mobile devices.

  • Be the first to comment

Beginning with basics of iOS

  1. 1. No. 01/2011 December 2011 www.icodermag.comBeginning with basics of iOSTreading New WatersStoryboard and ARCTop Errors andRisks in iOSThe All New iOS 5Siri – Worth the Hype?Getting Your First App to MarketGets You Paid – It Doesn’t Have To Be Good
  2. 2. december 2011 Greetings iCoders! Especially for You we started iCoder magazine. First issue is about iOS fundamentals and iOS 5 new features, but don’t think iCoder is only for beginners, everyone interested in Apple mobile operating system programming will find something interesting. Our magazine is made by programmers for programmers, so You will find here a lot of interesting and useful stuff like full articles about iOS programming, tutorials, reviews, app and accessories tests, information about new frameworks and plug-ins for xcode. We’re open for Your feedback and cooperation, so don’t hesitate and write to us if You have any suggestions about iCoder magazine or want to submit an article or any other useful feedback. It’s You who can make iCoder the best magazine about iOS programming in the world. Have a good reading and come back for more. Maciej Michałowski Editor in Chief icoder magazine Production director: Published by: Ałła Zalewska FX Press Sp. z o.o. Sp.K. Postal Address: President: FX Press Sp. z o.o. Sp.K., Ałła Zalewska ul. Bokserska 1, 02-682 Warszawa, Poland tel. +48 600 649 676 editor in chief: Maciej Michałowski Advertising: editors: All trade marks presented in the magazine were used Ewa Zasadzka only for informative purposes. All rights to trade marks Michał Pietruszkiewicz presented in the magazine are reserved by the companies Rafał Przybylski which own them. The FX Press Sp. z o.o. Sp.K. works individually from design and dTP: Apple. The iCoder Magazine team reserves the right Aneta Jones not to be responsible for the topicality, correctness, Eurodesign completeness or quality of the information provided by contributors.2 01/2011
  3. 3. conTenTs TuTORIAl beginning with basics of ios 5 Softweb Solutions Inc. Getting Your First App to market Gets You Paid – It doesn’t Have To be Good 8 Ian Marriot IOS API Treading new Waters, storyboard and Arc 13 Li Mengran WHAT’S NEW IN IOS The All new ios 5 22 Manish Nath SECuRITY Top errors and risks in ios – should be addressed by the developers 27 Krzysztof Wołk REvIEW siri – Worth the Hype 31 Alex Allegro3 01/2011
  4. 4. TuTorIAl beginning with basics of ios Softweb Solutions Inc. The author, Softweb Solutions is an ISO 9001:2008 Certified and Microsoft Gold Certified, Chicago- based IT service Provider Company that offers industry specified solutions through its knowledge and expertise. Combining unparalleled experience with the state of the art technical competencies, Softweb Solutions provides outstanding solutions to its global clients. The company offers end to end solutions for Custom Web Application Development, Mobile Application Development, eCommerce Development, Mobile SEO, Rich Internet Application development, Legacy Migration, et al. AbouT Ios The iOS – previously known as iPhone OS is an Operating System of Apple Inc. for all its mobile devices. The iOS is the heart of iPhone, iPad, and iPod Touch de- vices. For designing and developing iOS applications, devel- opers use Xcode and IDE [Apple’s integrated development environment]. Xcode is used to design the user interface of the application as it provides all necessary tools for writing the code for it. After developing the application for iOS, user can run it on iPhone, iPad, Mac, and iPod Touch devices. After the completion of designing and developing the iOS application, it is needed to be submitted to the App Store – the secure market place where iOS users get their applica- tions. Courtesy: The Operating system - iOS manages the device hardware layers of ios: and provides the technologies that are required to implement native apps. The iOS SDK have all the tools and interfaces that are needed to develop, install, run, and test the native ap- plications. The native apps are physically installed on an Apple device and therefore they are always available to the Apple users, even in the Airplane mode. THe Ios ArcHITecTure The iOS architecture is similar to the basic architecture found in Mac OS X. At the highest level, iOS acts as an intermediary between the underlying hardware and the applications that appear on the screen, as shown in the VersIons HIsTorY oF Ios below figure. The applications we create rarely talk to the Being an early adopter of Mobile Technologies, it is easier underlying hardware directly. Instead, applications com- for Softweb Solutions to explain the whole history of iOS municate with the hardware through a set of well-defined versions. Let us have a look at the gradual development of system interfaces that protect the application from hard- iOS. ware changes. This abstraction makes it easy to write ap- On 29th June, 2007, Apple Inc. released the first version plications that work consistently on devices with different of iOS with the first iPhone. hardware capabilities. On 11th July, 2008, Apple publicly released iPhone OS5 01/2011
  5. 5. beGInnInG WITH bAsIcs oF Ios TuTorIAl 2.0, with later upgrades of version 2.2 available for all mo- buIldInG Ios APPlIcATIon dels. The major release of 2.0 became available with the Before developing a new iOS application, it is important to fa- release of iPhone 3G. miliarize yourself with the basic concepts, fundamental design On 17th June, 2009, iOS version 3.0 was released with patterns and techniques. Basically, iOS assumes that all the upgraded through version 3.1.3. 3.0 version became ava- applications are built using the Model-View-Controller design ilable with the iPhone 3GS. First generation Apple devices pattern. Here we, Softweb Solutions explains the steps to – iPhone and iPod Touch has iOS version 3.1.3. build the simplest application “Hello World”. Later iPad was released with iOS 3.2 version which was specifically designed for the iPad. steps for building “Hello World” application – Later on 21st June, 2010, iOS 4.0 was released available 1] Open Xcode and click File > New Project. Select View-based- only to iPhone 4.0 and iPod Touch. While the second ge- application and click “Choose” button. After choosing, name the neration iPod Touch and iPhone 3G devices have iOS 4.2.1 project as “Hello World” and save it. After saving the project, you as their latest version. The first version to get major equ- will have a template for your Hello World iPhone Project. ivalent features to the iPhone and iPad is iOS 4.2. Later the sequence of iOS 4.2 was continued for the CDMA iPhone 2] Click on “Build and Go” button to run this template appli- and 4.3 was released for other devices as an upgrade. cation which will start an iPhone stimulator. After that clicking On 6th June, 2011, Apple previewed iOS version 5, Ap- on the “Home” button will show you a “Hello World” icon ple TV 4.4 beta, and iOS SDK 5 beta along with iCloud on the iPhone stimulator dashboard. Clicking it again will open beta. This update also introduced iMessage chat feature wi- the application. That is why, iPhone stimulator is considered thin the devices running on iOS 5.0. With iMessage feature, as the best tool to test the application before deployment or users can send messages to other iPhones, iPad, and iPod before submitting the application to the Apple Store. Touch users, so that they don’t have to pay extra for text messages. Other additions made in iOS 5 are – new notification system, Newsstand subscription, integrated Twitter, re- minders application, enhancements to AirPlay, and over 200 other new features. Moreover, it supports all iPad mo- dels, iPhone 3GS, iPhone 4 GSM, iPhone 4 CDMA, iPod Touch – 3rd and 4th generation. This version release has taken iOS to the whole new 3] Now you need to open the Xcode Project and select level. The camera application of this version offers many “HelloWorldViewController.h” file and type the below new in-built useful features like in-built editing feature, lock code inside the interface – screen access to camera, volume up button use for clicking a photo, and others. IBOutlet UITextField *txtUserName; IBOutlet UILabel *lblUserTypedName; APPle – ITunes Also write this method before end of this class iTunes is how users play all their media on their Mac or PC and - (IBAction) submitYourName; add it to their Apple devices. iTunes is a computer program used for media playing, downloading, and organizing any digital music or 4] After you write the above code, your video files on the PC. It is also capable to manage contents on iPod, “HelloWorldViewController.h” file will look like below – iPhone, iPad, and iPod Touch. It’s very simple to use and understand. Search any required me- #import <UIKit/UIKit.h> dia file on iTunes that you are looking for, and sync it with your @interface HelloWorldViewController: Apple device to get it. Basically, iTunes has become the central hub UIViewController { of media world for all the Apple users. IBOutlet UITextField *txtUserName; Originally, iTunes was specifically released as a music store but la- IBOutlet UILabel *lblUserTypedName; ter in the subsequent versions of it, all other type of entertainment } were also supported that includes radio, films, apps, television - (IBAction) submitYourName; shows, and audio books. The purchase history can be also seen by @end clicking the “purchase history” button after opening iTunes.6 01/2011
  6. 6. beGInnInG WITH bAsIcs oF Ios TuTorIAl 5] The next step is to open “HelloWorldViewController.m” Final output of this “Hello World” Application file and type the following method before @end – (IBAction) submitYourName; { lblUserTypedName.text = txtUserName.text; } 6] Design on Interface builder – Open Xcode project and in it “Group and Files”. Looking at bottom you will find “NIB Files” in which you will find two design files for your classes when you expand it. One is MainWindow.xib – main window or entry point to the app and second one is HelloWorldViewController.xib file which is mapped to your controller class. Double click on the second class to open it inside the interface builder. 7] Click on Tools > Library and drag the text field into your View. After this, click on Tools > Inspector and write “Your Name” in the text field. dIFFerence beTWeen THe code For An 8] After typing your name, drag the text field from Library IPHone APPlIcATIon And IPAd APPlIcATIon to your view and also drag another Label inside View. Click on tools then and select “Size Inspector” and also change For iPad the width of the text field to 250. Also change the layout if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceI- center. diomPad) { 9] Last thing to do is to drag a button to the view (19) and WhatIsViewController *VC1 = [[WhatIsViewController alloc] then open Inspector again by selecting Tools > Inspector. initWithNibName:@”What_ipad” bundle:nil]; In the Title, type “Submit”. [self.navigationController pushViewController:VC1 animated:YES]; 10] Map the controller class variable function and methods [VC1 release]; with interface builder. From Interface builder, select “File’s } Owner” and from Tools, select “Connection Inspector”. For iPhone 11] After selecting them, you will see that two new vari- { ables are added in Connection Inspector – txtUserName WhatIsViewController *VC1 = [[WhatIsViewController alloc] and lblUserTypedName. You need to click on txtUser- initWithNibName:@” What_iphone” bundle:nil]; Name radio button and drag it to text field in View. Next [self.navigationController pushViewController:VC1 you need to do same with lblUserTypedName, that is, se- animated:YES]; lect radio button and drag it below label. [VC1 release]; } 12] Last thing you need to do is click on the “submitYour- Name” radio button and drag it to the button and then select touch down from the list. Although we may not be sure what will be next in iOS, be with us to keep in touch with the industry develop- 13] Finally close the interface and open Xcode. Then sim- ments. The authors of this article have taken utmost care ply press “Build and Go” button to run this “Hello World” in disseminating the information here but assume no re- Application. It will open the stimulator in iPhone. sponsibility for any kind of errors.7 01/2011
  7. 7. TuTorIAl Getting Your First App to market Gets You Paid – It doesn’t Have to be Good Ian Marriott Two years ago, I knew as much about making an app as loves a superhero. And everybody seems to love phys- I currently do about the political situation in Sweden, ics based action puzzle games at the moment. I must that is to say, very very little. It’s not that I wasn’t in- be on to a winner. Not only that, but what I’ve got so terested, I had always been an avid gamer, and dreamed far is cool to play. And what’s more, your abilities came up ways in which the current crop of games could be with choices. Protect or Destroy? Hero or Villain? What better, and how I’d do it right if I ever made a game by could possibly go wrong? myself. Then, I was reading a magazine, and came across an article about a game engine that was free, yet power- Turns out I wasn’t as clever as I thought I was (this has ful enough that some pretty big name studios were using been a running theme throughout my adult life). I’d nev- it. I decided to give it a go. That engine was Unity, and er even seen XCode before, and it was a labyrinth that it’s ridiculously flexible, easy to use and, in my opinion, would make David Bowie stop in his tracks and think, the best way to start creating apps for beginners on the “Me and my floating glass balls better leave that place market. (See: “Coding Isn’t What it Used to Be…”). well alone.” Figuring that out took a good couple of days. Thankfully, Unity does a fantastic job of creating One year ago, I lost my job. My partner was pregnant the project files for you, all you have to do is figure with our second child. To say I was motivated to do out the provisioning system. Oh, yes, the provisioning something… anything… to put food on the table would system… (See “Provisionally Provision for Provisioning be an underestimation of the heat that the burning caul- Provisions”) dron of poverty, on fire centimetres beneath me, had created. But what to do? The economic climate didn’t fill Then, despite the fact that I’d gone into iOS develop- me with confidence, but app development did. It seemed ment, I didn’t actually have an iPhone. Or an iPod Touch. like a great passive income stream, the market was (and Or an iPad. Or a Mac (contentious I know, but a virtual still is) expanding extremely quickly and it felt like if machine image on my Windows laptop had to suffice I was ever going to get on board that particular train, I’d for the first 3 apps). I knew the specifications of each better do it before another big company wanted me to device, but didn’t actually have one on which to test. do some extremely tedious things for very little money This was a mistake on so many levels. It was like trying again… I’d spent a bit of time with the engine at this to build a house without foundations. On a lake. Using point, and with what little money I had, stumped up for air. Installing my app on a device was next to impossible, the iOS license for it, alongside joining the iOS devel- I had to visit my brother after he’d returned from work oper program. I decided I was going to make a run at it. just to spend 20 minutes testing to find as many bugs as possible. Then the next day I’d try to fix those bugs, I’d been working on an idea for a couple of months be- but not be able to check for another 2 days whether it fore that, which seemed to be taking shape quite nicely, had worked. Everything I did was a guess. An educated and thought it would be a perfect fit for the iPhone guess, but a guess nonetheless. I’d already spent in ex- market. I was developing a superhero physics action puz- cess of five hundred dollars though, and in the situation zler. The basic premise was good, in my eyes. Everybody I was in, I couldn’t afford to buy a device of my own.8 01/2011
  8. 8. GeTTInG Your FIrsT APP... TuTorIAl Working this way forced me, quickly, to optimise my but I was straight on Facebook telling people to get on code. Everything became ‘hacky’. What started as iTunes. The game was on “New & Noteworthy” lists a smooth 80fps on the computer screen quickly got around the world and got thousands of downloads in its bogged down to one tenth of that on the device. Each first day of sale. My ad revenue came in thick and fast, level had about two hundred rigidbodies in, each collid- and I was seeing an ECPM (earnings per thousand im- ing with at least 2 others.The A4 processor just could pressions) around the hundred dollar mark. This was ex- not cope with what I was throwing at it. I tried to help tremely surprising as all the research I’d done suggested as best I could, cutting down the texture quality, not ten dollars was average. I started to think there might rendering the (originally beautiful) 3D skyline I’d cre- be hope, and that this game was actually good, just not ated. Removing any shader that took up any processing as good as I’d intended so I was disappointed, but good time of statistical significance. Everything that I could enough for the people downloading it. cut out I did. A bastardised version of my original pro- ject emerged, shaking, stuttering to life, and barely func- Once more, I was mistaken. The reviews the game re- tional. It was a horrific mess, and was about as fun to ceived were mediocre, at best. They were accurate and play as “Where’s the Soap” in a prison shower. As each fair, and generally, through what little playing I’d done feature got stripped down, what remained felt like less of my own game, I agreed with them. When I finally got than the sum of its parts. The only thing that worked the chance to play it though, a few things dawned on was the menu system. Without being able to test, me – Firstly, most people download a game from the I’d had to create a User Interface (UI) that worked on description and screenshots that you put into iTunes all screen sizes, dynamically changing to suit the orienta- Connect. They don’t look at reviews, and they rarely tion or resolution of the screen (not that the resolution read past the first four lines of your blurb. No matter ever changed on an iOS device, but you do have to cater how poor an app is, if it looks good, a lot of people for different devices), and this is probably the most use- will download it, which means you’ll get some money ful skill I learned from the entire project. back through the adverts. Second, nobody cares about a good menu system provided it works. They care about At this point, you already know that your product is a playable game. Mine wasn’t playable. This would have simply not up to scratch. You can polish and polish, but to be corrected for the future… and third, but probably it’ll just end up being a shiny turd, so I decided it was quite important, is to make sure that if you have an ad going to have to do. I couldn’t start over, I had to get supported game, make sure the adverts don’t show up a product out there, I needed the money more than upside down, cover half of your level select screen, and I needed artistic credibility, so I wrote the blurb, took randomly appear and disappear. It makes people acci- some screenshots, optimised the keywords and then… dently click on your ads, which generates quite a bit of I had no idea how I was going to make money from it. revenue, but is against the Terms of Service agreement Could I justify charging for a product that was substand- you hold with Apple and makes you look like a scumbag. ard? Of course, for me, the answer to that was a big I swear, in all the tests I’d done, this wasn’t happening… fat “No”. It had to be free. So, the only option was to integrate adverts in the product. This was done quick- Eventually, I had to remove the abomination from the ly (thanks to Prime31 – See: “Making Life Easier”) and app store completely. It wasn’t just bad, it was broken. then it was a case of figuring out Application Loader, and No amount of updating would have fixed it. Now that sending the package for review (See: “Final Hurdles”). I know what I’m doing a little better, I might return to I didn’t know what to expect at all. Judging by what peo- the idea, but it would be a ground up build. The game ple say about the review process, I was in severe doubt had to be put out of it’s misery. But not before I’d gar- as to whether or not my game would be accepted. And nered some information about sales trends on the app from the research I’d done, it was unlikely that I was store (See: “We Consume All That Is New!”). going to make the money back that I’d already spent, let alone an income to live on… Even through all this however, my initial foray into the world of app development was successful. Despite (or per- Fortunately, after two agonising weeks, the game fi- haps because of ) my naivety, it earned me enough money nally got approved. I couldn’t even download it myself, to buy a small range of test devices for my future projects,9 01/2011
  9. 9. GeTTInG Your FIrsT APP... TuTorIAl and fund the development of the next one. It was four but it’s important to set up before you do any testing on further apps down the line that my releases were good an actual device. There are two types of profile that you enough to produce the same kind of figures I’d accidently require, a development profile, for which you need to use stumbled into with my first, and I still have to be prolific specific devices, and a distribution profile for, erm, distri- with my releases to earn a wage. I’ll have had eleven apps bution. released in the first year of being a developer, with at least the same again planned for next year. My baseline To set up a development profile, first you must set up income for these projects, not including the initial sales at least one device on which to test. You need to get spike, works out about a dollar a day, per app. The initial the UDID number of the device, which can be found in sales spike on average buys an iPad. It’s unlikely to make iTunes, or for ease, search “UDID” on the app store and you rich, but as a passive income generator it helps. download one of the free apps from there Go to the iOS development portal and click the “Provisioning Portal” Becoming an app developer has, without a doubt, changed option at the top right, then click “Add Devices” and fill my life for the better. I’d recommend it to anybody with in the form you’re presented with. the drive and determination to keep at it, and make it work for them. Your first forays into the app world prob- Once the device is set up, you need to set up a new “App ably won’t set the world ablaze, and will likely be full of ID”, so in the provisioning portal, click “App ID”, and mistakes, bugs (sorry, features) and plain bad design, but “New App ID”, then fill in the details as shown below: that isn’t what’s important. What matters is getting your app out there in the market, showing you that it can gen- erate some income, regardless of its quality. Put your work out there for the world to see and be proud to say that not only are you learning, but you are doing. And you are getting paid to do it. codInG Isn’T WHAT IT used To be… Unity ( is the most flexible game engine I’ve ever had the pleasure of using. In terms of 2D games, there are probably better solutions, but with the third party add-ons available through the Unity As- set Store, they won’t be that much better. In terms of 3D engines, it’s not Unreal, but take a look at games like Shadowgun and you’ll see what it’s capable of graphically. From a code based standpoint, you can use C# or Uni- The next step is to create the development provisioning tyScript (a version of JavaScript, so if you’re familiar with profile itself. Click the “Provisioning” tab on the left hand web development you’ll have no trouble picking it up). side, now, in the main box, create a new development You don’t have to worry as much about coding with Unity profile by clicking “New Profile”. A form like this should as you would in practically any other engine, although appear: it’s worth noting that you WILL need to get your head around the basics at least, especially as an Indy where you have to be a Jack of all trades. There are loads of tutorials to help you through this, and a pretty helpful community if you’re not trying to leap in and make the next World of Warcraft without knowing the difference between a rigidbody and a collider. ProVIsIonAllY ProVIsIon Make sure the fields are filled in, your App ID is selected, For ProVIsIonInG ProVIsIons and your testing devices are selected. Your app will only When making an app, provisioning can be an afterthought, work on devices that you have chosen to develop for, and10 01/2011
  10. 10. GeTTInG Your FIrsT APP... TuTorIAl have the UDID’s registered. Submit the form. Now, it may FInAl Hurdles say that your profile is “Pending”. Refresh the page and So, you’ve completed your app and it’s ready to be sent to you will be able to download it. Once downloaded, sim- Apple, but there are a few final hurdles and hoops to jump ply open the file in XCode and it will be ready for use. through. One issue that many people come across is non- Repeat these steps, without the specific devices, under public API use. Don’t do it, they’ll find it and reject your Provisioning>Distribution for your distribution certificate. binary, which means more work for you later and scuppers The final step is to then attach this profile to your app in your release plans. To upload your binary to Apple’s serv- XCode. In the app settings, scroll down to “Code Signing”, ers you’ll need to use Application Loader. Set up the binary and make sure that the signing identity is set as the profile as “Ready for Upload” in iTunes Connect, the run Appli- you just created: cation Loader, select the option to upload your package, choose your app ID from the drop down list and upload your binary (If you haven’t built for archiving in XCode, you’ll need to zip your .app file and send that, otherwise just use the zip file of your app) and hope that you don’t get any failure notices. Any of these that come up are eas- ily fixed in general, just Google the specific issue you get. Your info.plist file might get you into trouble here, make sure that the UIRequiredCapabilities array is correctly set up and that the build settings match (ie, armv6 or armv7 – And that’s it! You should now be able to build your app and I only ever build for armv7 devices now as pre-3gs install it on a device. Testing in the XCode environment iPhones and Generation 2 or lower iPod touches are such works quite well, but if you are using Unity, this will not a small share of the market, and don’t support iAd). be an option. Some people use the Unity Remote, I prefer to install on the device and see how it actually runs. I’ve Once your binary is “Waiting for Review”, you simply learned my lessons the hard way on that one. have to wait. The Apple staff get through the submissions pretty quickly, considering the number they receive. For mAkInG lIFe eAsIer a new app, it takes about ten working days to be approved, Anybody that has had anything to do with Unity will sometimes longer, but not often. For an update, about five know about the plug-ins that can be used, and anybody in working days is average. Then, you’re good to go. Or not. iOS development with Unity will have heard of Prime31 Rejections don’t come about too often if you keep to the ( The plug-ins that this company submission guidelines, but occasionally you’ll have made an have developed are staggeringly useful, priced extremely error that’s slipped through testing, or you’ll be pushing fairly, get customer support in a way that we should all a boundary, or (please god no) you’ll have submitted a fart aspire to and are installed in a huge number of iOS apps, soundboard. When you are rejected, generally you get including every single one of mine. It makes calling native a specific reason for it, which you can then go about in functions on iOS easy (and offered for free), improves on a couple of ways. The first way, you can complain, moan, the inbuilt Unity GUI system (also free), integrates with berate and cry about it, get people’s backs up and make life Facebook and Twitter with about 2 lines of code, uses Ap- harder for you in future. The second is that you can fix the ple’s GameCenter for scores, achievements, turn based problems, whatever they may be, and resubmit your app. and real time multiplayer, integrates adverts through a ton The second way usually works better… of different portals and uses StoreKit for in-app purchas- es. There are multiple other plug-ins that are offered too We consume All THAT Is neW! which increase functionality still further, making what can Apps available on the App Store have an extremely ‘long be a quite complicated and somewhat annoying process tail’. They continue to move a few units every day for a complete breeze. If there’s one company that has allowed months, maybe even years, after release. However, most of me to build a portfolio of apps quickly, it’s Prime31. your downloads (unless you get featured by Apple them- selves, get yourself reviewed or featured on a big site like Toucharcade or TechCrunch, or you invest in a program like FAAD) will come in the first few days of release. This is the graph for downloads of my first release, although11 01/2011
  11. 11. GeTTInG Your FIrsT APP... TuTorIAl due to restrictions in the developer license, specific numbers have had to be removed: As you can see from these daily figures, the first day is the most crucial. I now release my apps on a Friday or Saturday to maximise these effects, as these are also the days where apps gain most impressions from the ad networks, as you can see from this graph of last weeks’ iAd requests (again, numbers removed as we’re prohibited from sharing specifics): About the author: Ian marriott Ian makes apps under the name EyeSix Games (, his latest release is Calm 2 It makes sense here that in order to maximise profitability you ( have to up that original spike as much as possible. Not only calm-2/id484539101?ls=1&mt=8) does this mean more initial downloads, but as there are less and can be followed @EyeSix releases at a weekend it means you get a higher chart placing, on Twitter. Sometimes he puts which in turn means you’re higher on the search results and pictures at a slight angle just gives the user a greater chance of finding your app. to annoy people.12 01/2011
  12. 12. ios API Treading new Waters, storyboard and Arc Li Mengran iOS 5 and Xcode 4 have recently been released, with many exciting new features such as storyboards, Automatic Reference Counting (ARC), GLKit, Core Image, iCloud and Twitter integration. For a complete reference, it’s better to read Apple’s release notes. However, that can be overwhelming and intimidating for a starting point, if one wants to quickly try out the shiny new toys. Therefore, like many others, I love reading hands-on tutorials and writing some test pro jects before reading the release notes. Having enjoyed a lot of good tutorials from the developer community in the past, I think I should pay back the community by contributing a simple tutorial. 1. InTroducTIon tions Use Storyboard and Use Automatic Reference This tutorial familiarizes you with two new features of IOS 5, Counting, as shown in Fig. 1; the first one for obvious storyboard and ARC, by going through example projects step reasons, the second one for ease of coding. by step. Along the way, we’ll also introduce some new handy shortcuts brought by Xcode 4. 2. sTorYboArd Storyboard is a much improved interface builder and a lot more. It eliminates for us a lot of hassles in interface design, especially transitions between different views. There are new two concepts introduced with story- board, scene and segue. A scene is a UIViewController Figure 1: New Project that manages all the contents in one screen, and a segue is a transition between two scenes. After we finish with the project creation wizard, take a look Usually an app only requires one storyboard, in which we at the Project Navigator on the left of the screen, as can draw all the scenes for our app and link them by segues, shown in Fig. 2. It should be opened by default. If not, you in a simple and intuitive manner. Finally we have a tool that lets can open the project navigator by going from the top menu us manage all the visual aspects of our programs seamlessly View g Navigators g Show Project Navigator. in one place. Unfortunately these shiny new features are only Notice the highlighted storyboard file there. Instead of the available on iOS 5. .nib file, we work with this file to draw our interfaces. Now In this section we’ll give a simple tutorial on storyboard click on this file to open it in the interface builder. and show some of the new shortcuts in interface building brought by Xcode 4. 2.1 first example In our first example, we are going to create an iPhone app with two views that can pass data strings to each other. Let’s begin by going from the top menu File g New g New Project, then select Single View Application. Select iPhone in the Device Family, and name our project as ”StoryBoardDemo”, and make sure to check the two op- Figure 2: Project Navigator13 01/2011
  13. 13. TreAdInG neW WATers, ios API sTorYboArd And Arc You should see a blank view created by the wizard, as shown • Hold the control key and drag the Text Field to in Fig. 3. This controller class for this view is ViewCon- ViewController.h, in between the start and end of troller, implemented in the files ViewController.h and the interface definition, as shown in Fig. 4. ViewController.m, which are created by the wizard. We • A small window should pop up as shown in Fig. 5. Let’s call ViewController a scene in our storyboard. We can set the name to be ”textField” and make sure you zoom in or out by right clicking on a blank area and selecting change the storage option to strong. We won’t the appropriate option. explain why we need to set it this way in this section, Notice the arrow from nowhere pointing at this scene. but one simple rule of thumb is that if you would It indicates the fact that this is the initial scene, the scene declare this IBOutlet as retain before IOS 4, that immediately shows up when we start our application. It is you need to set its storage option to strong. very important to set the initial scene. In this example, the • Click Connect. wizard automatically sets it for us. However, if you are starting • Do the same for the Label and name it ”outputLabel”. from other templates, you may need to set it manually. You can do that in three steps: • Click on a scene to select it. • Open the attributes inspector by going from top menu View g Utilities g Show Attributes Inspector. • Check the option Is Initial View Controller. Figure 4: Assistant Editor1 Figure 3: Initial Scene Drag from the object library to the initial scene a Text Field, a Round Rect Button and a Label. Double click on the button and change its text to ”Switch To New View”. We’ll be using the Text Field to collect some user input, and the Label to display some string passed by the other Figure 5: Assistant Editor2 view which we are going to create in a short while. Therefore we need to hook up the Text Field and La- This should add the following two proper- bel to some IBOutlet in ViewController. we now show ties in ViewController.h and synthesize them in how to do it with a cool new shortcut brought by Xcode 4. ViewController.m, in addition to hooking them up to the right parts. • Go from top menu View g Assistant Editor g Show Assistant Editor to open the assistant editor. @property (strong, nonatomic) IBOutlet By default, you should see the editor and assistant UITextField *textField; editor opened side by side, and ViewController.h @property (strong, nonatomic) IBOutlet is automatically opened in the assistant editor window. UILabel *outputLabel;14 01/2011
  14. 14. TreAdInG neW WATers, ios API sTorYboArd And Arc That’s pretty neat, isn’t it. Now close the assistant editor File, then select UIViewController subclass, and then by clicking on the cross button in the top right corner of give it the name NewVewController. When you are pre- its window. sented with the options, remember to uncheck Targeted Right now the onscreen keyboard doesn’t retract when for iPad and With XIB for user interface. we finish entering in the Text Field. We have to write an IBAction handler to do that. Open the storyboard in the editor by clicking it in the Add the following definition in ViewController.h: Project Navigator. Click on the new View Controller to select it. Open the Identity Inspector by going from - (IBAction)textFieldReturn:(id)sender; top menu View g Utilities g Show Identity In- Add the following method body in ViewController.m: spector. In the Custom Class tab in Identity Inspec- - (IBAction)textFieldReturn:(id)sender tor, open the class drop down menu as shown in Figure. 7, { and select NewViewController. [sender resignFirstResponder]; } Basically this handler asks the first responder, in this case the onscreen keyboard to retract. Open the storyboard and click on the Text Field to select it. Open the Connections Inspector by going from top menu View g Utilities g Show Connections Inspector. In the Sent Events tab, while holding the con- trol key, drag from the circle to the right of Did End On Exit to the View Controller button at the bottom as shown in Fig. 6. A small black window should popup with only one option textFieldReturn. Select it should work as we want now. Figure 7: New View Controller Identity Draw a Text Field, Round Rect Button and Label on the new View Controller in a similar fashion as our original View Controller. Change the text on the button to ”Switch To Old View”. Also remember to make the onscreen keyboard for the new Text Field retract in a similar manner. Hook the Text Field to the property textField and Label to the property outputLabel in NewViewCon- troller in a similar fashion as the original view. Now is the time to create the segue! While holding the control key, drag the button in the original View Control- ler to the new View Controller, as shown in Fig. 8. Figure 6: Text Field Return Drag a View Controller from the object library to the storyboard. We need to create a new class for this new View Controller. Right click on the StoryBoardDemo group and select New Figure 8: Create Segue 115 01/2011
  15. 15. TreAdInG neW WATers, ios API sTorYboArd And Arc A small black window with three options should pop up, needed to create another segue from the new View Con- as shown in Fig. 9. Select modal from the options. The troller to the old View Controller. This doesn’t work, modal style segue is such that the new screen completely because every time a segue is invoked to transition from blocks the underlying screen, with which the user cannot a source View Controller to a destination View Con- interact until the screen on top is closed. The push style troller, it actually creates a new instance of the destina- segue is only for view controllers embedded in UINaviga- tion View Controller. Instead of going back to the source tionControllers or UITabBarControllers. If we use it here, scene, the segue I envisaged would just go to a new instance it doesn’t work. of the source scene. There is no ”reverse” segue per se. In order to go back, we need to close the new scene. Add the following IBAction handler definition in NewViewController.h. - (IBAction)buttonPress:(id)sender; Figure 9: Create Segue 2 Add the following IBAction handler implementation in You should see something like this in your storyboard, NewViewController.m. as shown in Fig. 10. - (IBAction)buttonPress:(id)sender{ [self dismissViewControllerAnimated:YES completion:nil]; } The dismissViewControllerAnimated:completion: method is new in iOS 5. It is different from the old method dismissModalViewControllerAnimated: in that it has an additional parameter, which is a block, that gives us the ability to execute additional code after the dismissal of the screen. The old method still works in IOS 5. Open the storyboard. Click on the button in the new Figure 10: Segue Created View Controller to select it, then while holding control key, drag it to the New View Controller button at the Notice the arrow with knot connecting the original View bottom, as shown in Fig. 11. Controller and the new View Controller. That repre- sents the segue. Select the segue by clicking on the knot. Open the Attributes Inspector. Set the identifier of the segue to ”OldToNew”. Note that we can also change the transition animation for this segue in the Attributes Inspec- tor. There are four types of transitions provided by UIKit, which we can subclass to customize. They are Cover Ver- tical, Flip Horizontal, Cross Dissolve and Par- tial Curve. By default, the transition for modal style seg- ue is Cover Vertical, which slides the destination scene vertically upwards to cover the source scene. Now we can already compile and see the transition to the new View Controller. Notice the convenience that this is done without having to write an IBAction handler for the button touch down event. However, there is no way to go back to the original screen yet. The first time I’ve tried Storyboard, I though I just Figure 11: Button Press 116 01/2011
  16. 16. TreAdInG neW WATers, ios API sTorYboArd And Arc Select buttonPress from the small black window that prepareForSegue:sender: to the following: pops up. Compile and run it; now pressing the button in the new scene should bring us back to the original. - (void)prepareForSegue:(UIStoryboardSegue *) segue sender:(id)sender{ Next we want to pass the string entered in the Text Field if([[segue identifier] isEqualToString: in the original View Controller to the new one and dis- @”OldToNew”]){ play it in the new one’s Label. We do this by importing NewViewController *nvc = (NewViewController *) NewViewController.h in ViewController.h, and imple- segue.destinationViewController; menting the method prepareForSegue:sender:, which nvc.msg = self.textField.text; is called by the system when the transition happens. } One initial try of the implementation is as follows: } - (void)prepareForSegue:(UIStoryboardSegue *) Uncomment the method viewDidLoad in segue sender:(id)sender{ NewViewController.m and change it to: if([[segue identifier] isEqualToString:@”OldToNew”]){ - (void)viewDidLoad NewViewController *nvc = (NewViewController *) { segue.destinationViewController; [super viewDidLoad]; nvc.outputLabel.text = self.textField.text; self.outputLabel.text = self.msg; } } } Now the string in the Text Field from the original view The idea here is to first check if it is the segue we want can be successfully displayed in the destination view. You to deal with by matching its identifier, then get a reference can try it to convince yourself. To pass back data from the to the destination View Controller, and set the text of destination View Controller to the original View Con- its outputLabel to the text in the Text Field of the troller, we need to add a protocol and delegate. original View Controller. However, this will not work, not because the text prop- Add in the definition for protocol NewViewControllerDel erty of the outputLabel is not set. The reason is that and the property delegate in NewViewController.h, so the method prepareForSegue:sender: is called after that NewViewController.h becomes the following: the creation of the instance of New View Controller, but before the loading of its view. As a result, when the #import <UIKit/UIKit.h> view of New View Controller loads, it overwrites the text property of outputLabel by the value we set in the story- @class NewViewController; board. One way to overcome this is to add to New View Con- @protocol NewViewControllerDel <NSObject> troller a new property that is not changed in the view - (void)newViewControllerClose: loading process, pass the value to that property and then (NewViewController*)controller; update the view in the viewDidLoad method of New View @end Controller. @interface NewViewController : UIViewController Add the following property definition in @property (strong, nonatomic) IBOutlet UIText- NewViewController.h: Field *textField; @property (strong, nonatomic) IBOutlet UILabel @property (strong, nonatomic) NSString *msg; *outputLabel; @property (strong, nonatomic) NSString *msg; Synthesize it as follows in NewViewController.m: @property (weak, nonatomic) id <NewViewCon- trollerDel> delegate; @synthesize msg; - (IBAction)buttonPress:(id)sender; - (IBAction)textFieldReturn:(id)sender; Change the implementation for the method @end17 01/2011
  17. 17. TreAdInG neW WATers, ios API sTorYboArd And Arc Note that it is customary to pass the reference of the ob- to tell the destination View Controller that the source ject calling the delegate function as the first parameter so View Controller is its delegate, like follows: that the delegate always knows who calls it. Usually this one parameter is enough, since we could pass messages to - (void)prepareForSegue:(UIStoryboardSegue *) the delegating object to retrieve whatever information segue sender:(id)sender{ we want. if([[segue identifier] Synthesize the property delegate in NewViewController.m isEqualToString:@”OldToNew”]){ as follows: NewViewController *nvc = (NewViewController *) segue.destinationViewController; @synthesize delegate; nvc.msg = self.textField.text; nvc.delegate = self; Note that the storage qualifier for property ”delegate” } is set to weak so as to avoid retain cycles, which we will } talk about later. Add in a line in the buttonPress method of NewView- Now the code should work as we want. Compile and run Controller to call the delegate method, like the following: it. Fig. 12 shows five screens. - (IBAction)buttonPress:(id)sender{ From top to bottom, left to right, the first screen is what [self.delegate newViewControllerClose:self]; we should see when we start the app; the second is after [self dismissViewControllerAnimated:YES we have entered the message ”hello world” in the Text completion:nil]; Field; the third one is after we click on the button and } transition to the new scene, where the message we’ve passed from the original scene is displayed below the but- Declare that ViewController now implements the ton; the fourth one is after we’ve entered the message protocol NewViewControllerDel in ViewController.h ”hello back” in the Text Field in the new scene; the last so that it is now the following: one is after we close the new scene, go back to the original scene and display the message passed from the new scene #import <UIKit/UIKit.h> below the button. #import “NewViewController.h” 2.2 Important Points To Take note @interface ViewController : UIViewController • Always remember to set an initial scene. It’s <NewViewControllerDel>; automatically set to be the default View Controller @property (strong, nonatomic) IBOutlet UIText- when you start with a single view project template. Field *textField; Should you start from some other template, e.g. the @property (strong, nonatomic) IBOutlet UILabel empty project template, you need to do it manually. *outputLabel; - (IBAction)textFieldReturn:(id)sender; • Segue always creates a new instance of the destination @end View Controller. Consequently it is not possible to create a ”reverse” segue, i.e. a segue that transitions Implement the protocol method NewViewController- back to the source View Controller. You have to do Close in ViewController.m like follows: it through delegate. - (void)newViewControllerClose: • Implement the prepareForSegue:sender: method (NewViewController*)controller; to pass data to the destination View Controller. { This method is called after the instance of the self.outputLabel.text = controller.textField. destination View Controller is created, but before its text; view is loaded. } • The push style segue is only used for scenes embedded Add in a line in the method prepareForSegue:sender: in UINavigationControllers or UITabBarControllers.18 01/2011
  18. 18. TreAdInG neW WATers, ios API sTorYboArd And Arc • We need to give each segue an identifier in order to this part into two subsections; the first one on how ARC differentiate between them. This identifier must be works, second one on interoperability with legacy code. unique in the scope of the source View Controller. That means different scenes may have segues sharing the 3.1 How Arc works same identifier. You need to enable ARC for it to work. You can do that when you start a new project, where the wizard presents 3. Arc, more subTle THAn IT seems you the option of enabling ARC, as shown in the previous The traditional IOS memory management model is all section. Checking that option enables ARC for the entire about the reference count, i.e. the number of references project. to an object from the other active objects in a lifecycle. The creator of the object has a reference to it; the other Basically ARC works by adding code at compile time to objects can increase the number of references to it if they ensure that objects live only as long as necessary, by adding call its retain method. The other objects can decrease retain, release and autorelease at appropriate plac- the reference count of the object in question by calling its es automatically. For example, below is code snippet for release method, to a non-negative number. They do it af- a typical object creation. ter they are done with the object. An object with zero ref- erence count in the end of the lifecycle will be deallocated. NSObject *obj = [[NSObject alloc] init]; However, if the creator of the object returns the object by // some code block a method, retain and release alone will not get us the behavious we want. Calling release on it will destroy it If obj is no longer used after some code block, the com- before the caller of the method could get it as the return piler automatically adds the invocation of the release value. On the other hand, not calling release on it before method on obj after the code block. If the obj is returned, we exit the method scope will cause memory leak. In this the compiler automatically adds the invocation of the au- case we call the method autorelease on the object, put- torelease method on obj. If we get reference to an au- ting it into an autorelease pool, which when destroyed by toreleased object like luckyNumArr in the following code, the system, will decrement the object’s reference count and later need to use it, the compiler can detect it and add by one. Great care has to be taken in order not to leak the call to retain method. memory, or create dangling pointers. Automatic Reference Counting, as its name suggests, luckyNumArr = [NSArray arrayWithObjects:tempArr is a feature that automatically counts the reference to an count:luckyCount]; object in our code and add the retain and release calls to it appropriately so that we humans do not have to both- The automatic deduction power of the compiler is pretty er any more. That sounds very nice, isn’t it. When I first powerful, but not always reliable. In particular, it does not heard about Automatic Reference Counting (ARC), I felt guard against retain cycle, which happens when for instance that it was too good to be true. Reading the release notes object A retains object B and object B retains A, resulting in details confirms my suspicion. There is no free lunch in a cycle of reference, preventing both objects from being in this world. To be fair, ARC does simplify a lot of work, deallocated. and I believe they will make it much better in the future. We can provide hints to the compiler by preceding our However, there are a lot of subtleties we have to take into property and variable declarations with lifetime quali- consideration, in order to make the best out of ARC and fiers. avoid ugly mistakes. • For properties, we have the qualifiers strong and In this section we will not develop any example apps, weak. We assign the qualifier strong to objects we as code snippets suffice for demonstration. Before you want to own, just as we assign retain when ARC is start to try ARC, make sure you at least have XCode 4 on disabled. The qualifier weak is like the qualifier assign Snow Leopard, because although ARC is mostly a compile- when ARC is disabled, except that when this property time trick, it does require some runtime support. You can is deallocated, the property value is set to nil, instead only target IOS 4 and above for IOS, or Snow Leopard and of remaining as a dangling pointer.Note that zeroing above for OSX. Besides, you need Xcode 4 in Lion to de- weak references only work on IOS 5 and above for velop apps with ARC enabled for Snow Leopard. We divide IOS, Lion and above for OSX.19 01/2011
  19. 19. TreAdInG neW WATers, ios API sTorYboArd And Arc retain, assign and copy qualifiers cannot be used with – ( __bridge_transfer T) p does the cast and ARC. Remember that we assign the qualifier strong to decrement the CFRef by 1. the Iboutlets in the storyboard section? The pattern – ( __bridge_retained T) p does the cast and we should typically adopt for the Iboutlets is that increment the CFRef by 1. they are all set to weak, except for those from File’s Owner to top-level objects in a nib file or a storyboard • We cannot use NSAutoreleasePool objects. Instead scene, which are set to strong. we should embed the codes benefitting from the autorelease pool in an @autoreleasepool block • For variables, we have the following qualifiers: like this: – __strong is the default qualifier if we do not specify @autoreleasepool{ anything. It means that we intend to own the object //code benefitting from the pool in question. } – __weak specifies a zeroing weak reference to an object. According to Apple, this is more efficient than using – __unsafe_unretained specifies weak reference to NSAutoreleasePool. an object that leaves the pointer dangling after it has been deallocated. There are some pitfalls we need to avoid. – __autoreleasing is used for arguments passed by reference id* and autoreleased on return. • We need to be careful when using __weak variables on the stack, as they are immediately released when there Besides the new qualifiers, ARC also introduces new rules. is no strong reference to it. For instance, consider the We list the more relevant rules here: following code snippet: • In order not to mess up ARC’s deduction algorithm, we NSArray __weak *list=[NSArray arrayWithObject cannot explicitly invoke dealloc, retain, release, s:@”Tom”,@”Jerry”,nil]; retainCount or autorelease. Neither can we try to [self displayList:list]; surreptitiously invoke them through selectors like @selector(retain). Although list is used after the assignment, there is no strong reference to it. Therefore it is immediately deallo- We may implement a dealloc method to manage cated, and the method displayList: will display nothing resources. since list will be set to nil before invoking display- List:. • We cannot use the foundation functions NSAllocateObject or NSDeallocateObject. • We also have to ensure that an object passed by reference have the same lifetime qualifier as the • We cannot use object pointers in C structures. corresponding argument declaration. For example, • We cannot casually cast between id and void *. if we have the following code snippet: We need to use the following three bridging casts to inform ARC about the ownership of the object OperationInfo *info = nil; in question: __bridge, __bridge _transfer, and BOOL OK = [myObject __bridge _retained. The latter two should only be doOperationWithInfo:&info]; used when dealing with toll-free bridged Core if(!OK){ Foundation objects where we would normally have // blah blah blah to call cFretain and/or cFrelease to manage the // ... lifetime of Core Foundation objects. It works and info is implicitly declared to be strong. Now – ( __bridge T) p casts p to the type T with no if the method declaration of doOperationWithInfo: operation at all. No ownership is transferred. is the following:20 01/2011
  20. 20. TreAdInG neW WATers, ios API sTorYboArd And Arc -(BOOL)doOperationWithInfo:(OperationInfo * have a graph of objects, we would like to have within it __autoreleasing *)info; a spanning tree, i.e. a strict parent-child hierarchy, where we set the reference from parent to child as strong and Then there is a mismatch between the lifetime qualifier child to parent as weak. This usually does the trick. of info and the argument to the method doOperation- WithInfo:. In this case, the compiler rewrites the code 3.2 Interoperability into: ARC can work on a file by file basis, meaning we could have files with ARC disabled in an ARC enabled project. We OperationInfo __strong *info = nil; can enable ARC using the new -fobjc-arc compiler flag. OperationInfo __autoreleasing *tmp = info; In a project where ARC is enabled by default, we can dis- BOOL OK = [myObject able ARC for a specific file using the new -fno-objc-arc doOperationWithInfo:&tmp]; compiler flag. One more thing to take note when we want info = tmp; a mixture of ARC enabled and disabled files is that we can if(!OK){ not give a property a name that begins with new. // blah blah blah // ... 4 conclusIon I hope this simple tutorial can help you start having fun This would create an unnecessary temporary variable. with the shiny new toys! We can rectify this by changing the type of the argument to the method doOperationWithInfo: to id __strong About the author: * or declare the variable info as __autoreleasing. li mengran • We need to carefully manage the lifetime qualifiers in The author is currently a PHD student order to avoid having a strong reference cycle, which in the National University of Singapore. is the same thing as the old retain cycle. When we Figure 12: Result21 01/2011
  21. 21. WHAT’s neW In ios The All new ios 5 Manish Nath Icloud sTorAGe APIs The contents of the block are enclosed by curly braces, Using the iCloud storage APIs as shown in the following example: a user can view or edit those documents from any device with- @autoreleasepool out having to sync or transfer { files explicitly. Storing documents // Your code here in a user’s iCloud account also provides a layer of secu- } rity for that user. With the new iCloud storage loosing your device does not mean that you loose your data. A storyboard file captures your entire user interface in There are two ways that applications can take advantage one place and lets you define both the individual view of iCloud storage, each of which has a different intended controllers and the transitions between those view con- usage: trollers. Storyboards capture the flow of your overall user interface. • iCloud document storage – Use this feature to store If you are creating new applications, the Xcode templates user documents and data in the user’s iCloud account. come preconfigured to use storyboards. For other applica- tions, the process for using storyboards is as follows: • iCloud key-value data storage – Use this feature to share small amounts of data among instances of your 1. Configure your application’s Info.plist file to use application. storyboards: AuTomATIc reFerence counTInG • Add the UIMainStoryboardFile key and set its value to Automatic Reference Counting (ARC) is a feature built the name of your storyboard file. to simplify the process of managingthe lifetimes of Objective-C objects. ARC evaluates the lifetime require- • Remove the existing NSMainNibFile key. (Storyboards ments of your objects and automatically inserts the ap- replace the main nib file.) propriate method calls at compile time. 2. Create and configure the storyboard file in Xcode Some Restrictions with ARC : cusTomIze nATIVe uI elemenTs In Ios 5 • Do not call the retain, release, autorelease, or dealloc You can now customize the appearance of many UIKit methods in your code. views and controls to give your application a unique look and feel. For example, you might use these customiza- • Do not store object pointers in C structures. tions to make the standard system controls match the branding for the rest of your application. • Do not directly cast between object and nonobject types (for example, between id and void*). UIKit supports the following customizations: • No NSAutoreleasePool objects. • You can set the tint color, background image, and title position properties (among other) on a wide variety of Instead, you must use a new @autoreleasepool keyword objects, including toolbars, navigation bars, search bars, to mark the start of an autorelease block. buttons, sliders, and some other controls.22 01/2011
  22. 22. THe All neW ios 5 WHAT’s neW In ios • You can set attributes of some objects directly, or you forBarMetrics:UIBarMetricsLandscapePho- can set the default attributes to use for a class using an ne]; appearance proxy. // Customize the title text for *all* UINavigationBars An appearance proxy is an object you use to modify [[UINavigationBar appearance] setTitleTe- the default appearance of visual objects such as views xtAttributes: and bar items. Classes that adopt the UIAppearance [NSDictionary dictionaryWithObjectsAnd- protocol support the use of an appearance proxy. To Keys: modify the default appearance of such a class, retrieve [UIColor colorWithRed:255.0/255.0 its proxy object using the appearance class method and green:255.0/255.0 blue:255.0/255.0 alpha:1.0], call the returned object’s methods to set new default UITextAttributeTextColor, values. A proxy object implements those methods and [UIColor colorWithRed:0.0 green:0.0 properties from its proxied class that are tagged with blue:0.0 alpha:0.8], the UI_APPEARANCE_SELECTOR macro. For exam- UITextAttributeTextShadowColor, ple, you can use a proxy object to change the default [NSValue valueWithUIOffset:UIOffset- tint color (through the progressTintColor or trackTint- Make(0, -1)], Color properties) of the UIProgressView class. UITextAttributeTextShadowOffset, If you want to set a different default appearance based [UIFont fontWithName:@”Arial-Bold” on how a given object is used in your application,you can size:0.0], do so using the proxy object returned by the appearance- UITextAttributeFont, WhenContainedIn: method instead. For example, you use nil]]; this proxy object to set specific default values for a button only when it is contained inside a navigation bar. } Any changes you make with a proxy object are applied, at view layout time, to all instances of the class that exist or uIbarbuttonItem that are subsequently created. [[UIBarButtonItem appearance] setBackgroundIma- code snIPPeTs: ge:button24 forState:UIControlStateNormal barMetrics:UIBarMetricsLandscapePhone]; navigationbar [[UIBarButtonItem appearance] setTitleTextAt- - (void)customizeAppearance tributes: { [NSDictionary dictionaryWithObjectsAndKeys: // Create resizable images [UIColor colorWithRed:220.0/255.0 gre- UIImage *gradientImage44 = [[UIImage image- en:104.0/255.0 blue:1.0/255.0 alpha:1.0], Named:@”surf_gradient_textured_44”] UITextAttributeTextColor, resizableImageWithCapInsets:UIEdgeInset- [UIColor colorWithRed:1.0 green:1.0 sMake(0, 0, 0, 0)]; blue:1.0 alpha:1.0], UIImage *gradientImage32 = [[UIImage image- UITextAttributeTextShadowColor, Named:@”surf_gradient_textured_32”] [NSValue valueWithUIOffset:UIOffsetMake(0, resizableImageWithCapInsets:UIEdgeInset- 1)], sMake(0, 0, 0, 0)]; UITextAttributeTextShadowOffset, [UIFont fontWithName:@”AmericanTypewri- // Set the background image for *all* UINavigationBars ter” size:0.0], [[UINavigationBar appearance] setBackgroun- UITextAttributeFont, dImage:gradientImage44 nil] forBarMetrics:UIBarMetricsDefault]; forState:UIControlStateNormal]; [[UINavigationBar appearance] setBackgroun- dImage:gradientImage3223 01/2011
  23. 23. THe All neW ios 5 WHAT’s neW In ios uITabbar uIswitch [[UITabBar appearance] setBackgroundImage:tab- [rentSwitch setOnTintColor:[UIColor colorWi- Background]; thRed:0 green:175.0/255.0 blue:176.0/255.0 al- [[UITabBar appearance] setSelectionIndicatorI- pha:1.0]]; mage: [UIImage imageNamed:@”tab_select_indi- cator”]]; sTorYboArds uIslider [[UISlider appearance] setMaximumTrackImage- :maxImage forState:UIControlStateNormal]; [[UISlider appearance] setMinimumTrackImage:mi- nImage forState:UIControlStateNormal]; [[UISlider appearance] setThumbImage:thumbImage forState:UIControlStateNormal]; uIsegmentedcontrol If you have an app with many different screens then storyboards can help reduce the amount of glue code [[UISegmentedControl appearance] setBackgroun- you have to write to go from one screen to the next. dImage:segmentUnselected Instead of using a separate nib file for each view controller, forState:UIControlStateNormal barMetrics:U- your app uses a single storyboard that contains the de- IBarMetricsDefault]; signs of all of these view controllers and the relationships [[UISegmentedControl appearance] setBackgroun- between them. dImage:segmentSelected forState:UIControlStateSelected barMetric- Storyboards have a number of advantages over s:UIBarMetricsDefault]; regular nibs: [[UISegmentedControl appearance] setDividerIma- • With a storyboard you have a better conceptual ge:segmentUnselectedUnselected overview of all the screens in your app and the forLeftSegmentState:UIControlStateNormal connections between them. It’s easier to keep track rightSegmentState:UIControlStateNormal of everything because the entire design is in a single file, barMetrics:UIBarMetricsDefault]; rather than spread out over many separate nibs. [[UISegmentedControl appearance] setDividerIma- ge:segmentSelectedUnselected • The storyboard describes the transitions between the forLeftSegmentState:UIControlStateSelected various screens. These transitions are called “segues” rightSegmentState:UIControlStateNormal and you create them by simply ctrl-dragging from one barMetrics:UIBarMetricsDefault]; view controller to the next. Thanks to segues you need [[UISegmentedControl appearance] less code to take care of your UI. setDividerImage:segUnselectedSelected forLeftSegmentState:UIControlStateNormal • Storyboards make working with table views a lot easier rightSegmentState:UIControlStateSelected with the new prototype cells and static cells features. barMetrics:UIBarMetricsDefault]; You can design your table views almost completely in the storyboard editor, something else that cuts down on the amount of code you have to write.24 01/2011
  24. 24. THe All neW ios 5 WHAT’s neW In ios oPenGl es 2.0 WITH GlkIT Json In Ios 5 iOS 5 comes with a new set of APIs that makes de- iOS 5 has some new built-in APIs to make it really easy veloping with OpenGL much easier than it used to be. to read and write JSON. Over a period of time JSON has The new set of APIs is collectively known as GLKit. proven itself best for communication with a web service It contains four main sections: . For example, if you have an array of three strings, the JSON representation would simply be: • GlkView/GlkViewcontroller. These classes abstract out much of the boilerplate code it used [“test1”, “test2”, “test3”] to take to set up a basic OpenGL ES project. If you have a Pet object with member variables name, • Glkeffects. These classes implement common shading breed, and age, the JSON representation would simply behaviors used in OpenGL ES 1.0, to make transitioning be: to OpenGL ES 2.0 easier. They’re also a handy way to get some basic lighting and texturing working. {“name” : “Dusty”, “breed”: “Poodle”, “age”: 7} • Glmath. Prior to iOS 5, pretty much every game It’s that simple, which is why it’s so easy and popular to needed their own math library with common vector use. The reason JSON is important is that many third and matrix manipulation routines. parties such as Google, Yahoo, or Kiva make web ser- vices that return JSON formatted data when you visit • GlkTextureloader. This class makes it much easier a URL with a specified query string. If you write your to load images as textures to be used in OpenGL. own web service, you’ll also probably find it really easy Rather than having to write a complicated method to convert your data to JSON when sending to another dealing with tons of different image formats, loading party. If you’ve had to parse JSON in your iOS apps in a texture is now a single method call! the past, you’ve probably used a third party library such as JSON Framework. Arc In Ios 5 The most disruptive change in iOS 5 is the addition of Well with iOS 5, needing to use a third party library Automatic Reference Counting, or ARC for short. ARC for JSON parsing is a thing of the past. Apple has finally is a feature of the new LLVM 3.0 compiler and it com- added a JSON library in Cocoa and I must say I person- pletely does away with the manual memory management ally like it very much! that all iOS developers love to hate. You can turn objects like NSString, NSNumber, NSArray Using ARC in your own projects is extremely simple. and NSDictionary into JSON data and vice versa super You keep programming as usual, except that you no easily. And of course no need to include external librar- longer call retain, release and autorelease. That’s basi- ies – everything is done natively and super fast. cally all there is to it. core ImAGe In Ios 5  With Automatic Reference Counting enabled, the com- Core Image is a powerful framework that lets you easily piler will automatically insert retain, release and autore- apply filters to images, such as modifying the vibrance, lease in the correct places in your program. To migrate hue, or exposure. It uses the GPU (or CPU, user defin- your current app to ARC you can Edit > Refactor menu, able) to process the image data and is very fast. Fast you’ll see an option called migrate to objective- enough to do real time processing of video frames! c Arc. That tool will help convert your code to Arc. Core Image filters can stacked together to apply multiple ef- fects to an image or video frame at once. When multiple fil- The only problem that you might face would be ters are stacked together they are efficient because they cre- with 3rd party libraries used in your app which ate a modified single filter that is applied to the image, instead might not support Arc. of processing the image through each filter, one at a time.25 01/2011