Best place to start iOS app development. Here we combine multiple sources to make iOS development simple and easy way.
Saturday, 31 August 2013
Friday, 30 August 2013
Best Practice iPhone SDK App Design
Best Practice iPhone SDK App Design
Presentation Transcript
- 1. "Best Practice" iPhone SDK App Design Bess Ho UI & iPhone Developer Silicon Valley Code Camp (SVCC) Oct 3-4, 2009 Foothill College Los Altos CA Twitter: bayareaparty
- 2. UI Developer / Architect Spock Bess Half Vulcan Half Developer Half Human Half Designer Pointed Ears Pointed Eyes “I am a Developer, Not a Designer”
- 3. Spock Bess Complex Mind Complex Background “It would be illogical to assume that all conditions remain stable.” - Spock “It would be illogical to assume that a good developer can’t design.” - Bess
- 4. Dancing Piano Dancing Drum Dancing Steel Drum Doctor Tricorder Sound Tricorder
- 5. Founder of Silicon Valley Web Builder (SVWB) Mentor Google Technology User Group (GTUG) Open Source Project “Chief Medical Officer” based on Google Health
- 6. 1st Book on Myspace Technical Editor 1st Book on Open Social Building OpenSocial Apps: A Field Guide to Working with the MySpace Platform Authors: Chris Cole, Chad Russell, Jessica Whyte Published Oct 23, 2009 Publisher: Addison-Wesley Professional. Part of the Developer's Library series.
- 7. One-Girl-Shop References Blog Featured by WordPress Based on “Objective-C” Tag http://webbuilders.wordpress.com/ Powerpoints http://www.slideshare.net/bess.ho Code Examples http://code.google.com/p/iphonebuilder/
- 8. What are we going Learn?
- 9. No. 1 One-Girl-Shop Shorten your design & development cycle Tips & Tricks
- 10. 2 No. Submission Requirements Apple Store Review Process Increase Your Chance of Approval Do & Do Not Lists
- 11. 3 No. Product Definition Design Better App Improve User Experience
- 12. No.4 Backup Anything impossible would be possible Backup your Artwork & Xcode projects
- 13. Approval Process Based on approvals process for iPhone applications, in a filing to the US Federal Communications Commission (FCC) in 2009 95% apps are approved within 14 days of submission Apple has 40 Full Time trained reviewers studying 8,500 new apps a week 20% “not approved as original submitted” but sent back to developer for tweaks & changes http://www.mobile-ent.biz/news/34116/Apple-reveals-some-details-about-App- Store-approval-process
- 14. Controversial Apps Based on approvals process for iPhone applications, in a filing to the US Federal Communications Commission (FCC) in 2009 “established an App Store executive review board that determines procedures and sets policy for the review process, as well as reviews applications that are escalated to the board because they raise new or complex issues.” The board meets once a week. http://www.mobile-ent.biz/news/34116/Apple-reveals-some-details-about-App- Store-approval-process
- 15. App Submission Required Images 512x512 JPG (Promotional Image) 480x320 JPG (Landscape App Image) 320x480 JPG (Portrait App Image)
- 16. iPhone SDK App Required Images 57x57 PNG Icon.png (App Icon) 29x29 PNG Icon-Small.png (Setting & Search Icon) 480x320 PNG Default.png (Landscape Loading Image) 320x480 PNG Default.png (Portrait Loading Image)
- 17. Prepare Images The standard bit depth for icons and images is 24 bits (8 bits each for red, green, and blue), plus an 8-bit alpha channel. The PNG format is recommended, because it preserves color depth and supports an embedded alpha channel. No need to constrain your palette to web- safe colors
- 18. Prepare Icons Start with highest resolution quality image Create 512x512 160+ dpi artwork Convert them into 3 sizes Save them to Apple preferred names Apple expects consistency in images 512x512 72 dpi app_icon.jpg 57x57 160+ dpi Icon.png 29x29 160+ dpi Icon-Small.png
- 19. App Icon Design 57x57 160+ dpi Icon.png By default 1) Apply round-corners 2) Apply shine 3) Apply Drop shadow Best investment Pick a color to position your app on the rainbow wall Apple tends to select & feature app with good icon design in stores, conferences and Ads Avoid using images similar to Apple icons & images
- 20. Info.plist
- 21. App Icon Design 29x29 160+ dpi Icon-Small.png Used to be Icon-Setting.png Every application should supply a small icon that iPhone OS can display when the application name matches a term in a Spotlight search. Applications that supply settings should also supply this icon to identify them in the built-in Settings application.
- 22. App Icon Design 57x57 160+ dpi Icon.png Remove default shine Add the UIPrerenderedIcon key to your application’s Info.plist file
- 23. App Icon Design 57x57 160+ dpi Icon.png Recommend to add your app name to your icon if your app name is too long to show on iphone home screen By default Bundle display name use your Xcode Project name Add App name to Info.plist file
- 24. Prepare Backgrounds Improve User Experience Make your loading image similar to your App Background if your app requires a longer loading time Default.png (Loading Image) background.png (App Background Image)
- 25. Image Location Icon.png, Icon-Setting.png, Default.png are suggested to saved at the root of Xcode project Organize images & audio files in Groups under “Resources” folder Drag & Drop entire folders into Xcode Project
- 26. System-Provided Buttons & Icons Toolbars & Navigation Bars Icon UIBarButtonSystemItem
- 27. Toolbars & Navigation Bars Icon UIBarButtonSystemItemDone, UIBarButtonItemStylePlain, UIBarButtonSystemItemCancel, UIBarButtonItemStyleBordered, UIBarButtonSystemItemEdit, UIBarButtonItemStyleDone UIBarButtonSystemItemSave, UIBarButtonSystemItemAdd, UIBarButtonSystemItemFlexibleSpace, UIBarButtonSystemItemFixedSpace, UIBarButtonSystemItemCompose, UIBarButtonSystemItemReply, UIBarButtonSystemItemAction, UIBarButtonSystemItemOrganize, UIBarButtonSystemItemBookmarks, UIBarButtonSystemItemSearch, UIBarButtonSystemItemRefresh, UIBarButtonSystemItemStop, UIBarButtonSystemItemCamera, UIBarButtonSystemItemTrash, UIBarButtonSystemItemPlay, UIBarButtonSystemItemPause, UIBarButtonSystemItemRewind, UIBarButtonSystemItemFastForward, UIBarButtonSystemItemUndo, / iPhoneOS 3.0 / UIBarButtonSystemItemRedo, / iPhoneOS 3.0 /
- 28. System-Provided Buttons & Icons Tab Bar Tabs Icon Table Rows
- 29. System-Provided Buttons & Icons Use pure white with appropriate alpha Do not include a drop shadow Use anti-aliasing Toolbar Icons Navigation Bar Icons Tab Bar Icons 20 x 20 pixels 30 x 30 pixels
- 30. iPhone Human Interface Guidelines http://developer.apple.com/safari/library/ documentation/InternetWeb/Conceptual/ iPhoneWebAppHIG/Introduction/ Introduction.html
- 31. Prepare Audio Most Popular Audio Methods AudioServicesPlaySystemSound AVAudioPlayer
- 32. Do Not DO NOT Copy-Right Materials (Image, Audio, etc) DO NOT use License Materials unless you have written documents to prove your ownership DO NOT use any Brand or Trademark names DO NOT use any images too similar to iphone system icons DO NOT submit app with warnings & errors DO NOT treat Apple Review Team as QA
- 33. Debug & Audit Test your app in both iPhone Simulator & Device Test your app in both iTouch & iPhone 50% users are on iTouch No Warning Console No Error Xcode Device
- 34. 1st / 2nd App Sound Tricroder & Doctor Tricorder 1st iPhone SDK Trekkie from TV to Movies Star Trek Movie Release in May Loyal Star Trek Fans Worldwide Tricorders in App Store Suck Poor Interface Old Generation Tricorder Few Low-quality Sound Barely Any Animations Entertainment Only
- 35. Explanation In Review 3 months Instead of crying Or beating up Apple iPhone Review Team Convert my anger & frustration to creating new app 2 months wait Shorten Development Not related to Cycle & Release Early technical issues
- 36. Product Definition Solve a sticky problem Create your own niche Create new market
- 37. Product Definition Solve a sticky problem Apple won’t approve SDK app that is similar to web Create your own niche app Create new market Apple won’t approve your app if it is similar to existing app in App Store Apple won’t approve your app if it doesn’t have enough features
- 38. Design Rules Keep it Simple Design for Dummies No Guessing Picture worths thousand words Do One Thing Really Well Less Touch = Clicks Fewer Screens = Page Load Fast Loading Lower Latency
- 39. Design Rules Make it Fun Use interesting images Use movements Engage users
- 40. Product Definition Dancing Series - Use Accelerometer Interests Target Strengths Want anyone without music I love music training can play I play music for years It is more entertaining and engaging to design app I love dancing involved movement I love design Music is universal with no language barrier All age groups All genders
- 41. Product Strategy Dancing Series Music Band Dancing Piano Dancing Drum Dancing Steel Drum Dancing Tambourine
- 42. Competition: Leading Drum Apps in Top 100 Drum Kit DigitDrummer $1.99 / Free $0.99 / Free Volume Control No Volume Control (Flip View) Pay $1.99 Extra Recording Recording
- 43. Marketing Positioning: Competitive Differentiation 1st Drum App uses Dancing Drum Accelerometer $0.99 Volume Control - Same View Brighter Cheerful More Sound Touch Play Motion Play Casual Play - All Ages Accelerometer > Record
- 44. Drum Kit Drum Kit Lite Free Rank: 12 Drum $1.99 Rank: 55 DigitDrummer DigiDrummer Lite Free Rank: 14 DigiDrummer Micro $0.99 Rank: 485 DigiDrummer $0.99 Rank: 62
- 45. Dancing Drum Dancing Drum $0.99 Rank: 1496 Not Perfect Shorten Development Cycle Release Early 1st Release 1.0 Bad Timing OS2.2.1 - OS3.0 Buried at the bottom in Release Date due to inexperience
- 46. Drum Kit DigitDrummer Dancing Drum 6 Drums 5 Cymbals 4 Drums 4 Cymbals 5 Drums 6 Cymbals + 5 Extra DigiDrummer Lite Free Rank: 14 Dancing Drum $0.99 Rank: 1495 Drum Kit Lite Free Rank: 12 DigiDrummer Micro $0.99 Rank: 485 Drum $1.99 Rank: 55 DigiDrummer $0.99 Rank: 62 2.2 Versions 1.0 Versions 2.6 Versions 1.1 Versions 54266 ratings 0 ratings 3035 ratings 18207 ratings 1.7 Versions 3.3 Versions 1212 ratings 2904 ratings Data from Moblix 6/22/09
- 47. DEMO Rank within Top 100 Rank: 1495 DigitDrummer Dancing Drum Drum Kit
- 48. Once In Your Lifetime Don’t make any Apple won’t allow you to mistakes in change Release Date once submitting your app the date is past Don’t keep changing Apple won’t allow you to get Release Date into Newly Release category after re-submit for update Save the right Category Prepare for your Launch & Marketing Campaign
- 49. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 50. Mockup Tools Paper Prototype 1 Paper + Pen 2 Metal Stencil $ 3 Online Prototype Sketching 4 Balsamiq stencils 5 Omnigraffle stencils 6 Visio template 7, 8, 9 Adobe Photoshop, Illustrator, Firework 10 Yahoo! Design Stencil Kit
- 51. Mockup Tools iPhone SDK IDEs 11 Dash Code (Drag & Drop) 12 Xcode’s Interface Builder (Drag & Drop) iPhone SDK Frameworks 13 Titanium (HTML / CSS / JS) 14 Phone Gap (HTML / CSS / JS) 15 Corona (Lua) 16 MonoTouch (C# .NET)
- 52. Mockup Tools iPhone Webkit Frameworks 17 iUI (HTML / CSS / JS) 18 CiUI (HTML / CSS / JS) 19 JQTouch (HTML / CSS / JS)
- 53. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 54. Paper Prototype Pen + Paper http://www.designcommission.net/stencils/ iphone_stencil_paper.pdf
- 55. Paper Prototype Downloadable .PDF letter or A4 sized printable template http://www.designcommission.com/shop/iphone- stencil-kit/
- 56. Paper Prototype http://labs.boulevart.be/index.php/2008/06/05/ sketch-paper-for-the-mobile-designer/
- 57. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 58. Online Prototype http://iphonemockup.lkmc.ch/
- 59. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 60. Blue Print http://www.flickr.com/photos/flingmedia/2734477874/
- 61. Balsamiq http://www.balsamiq.com/
- 62. Omnigraffle Stencils http://www.graffletopia.com/search/iphone
- 63. Adobe Illustrator & Photoshop http:// http:// www.mercuryintermedia.com/ www.teehanlax.com/ blog/index.php/2009/03/iphone- blog/?p=1628 ui-vector-elements/
- 64. Adobe Firework CS3 & CS4 http://blog.metaspark.com/2009/02/fireworks-toolkit-for- creating-iphone-ui-mockups/
- 65. Yahoo! Design Stencil Kit OmniGraffle, Visio (XML), Adobe Illustrator (PDF and SVG), and Adobe Photoshop (PNG) http://developer.yahoo.com/ypatterns/about/stencils/
- 66. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 67. iPhone SDK Dash Code http://developer.apple.com/iphone/library/documentation/AppleApplications/ Conceptual/Dashcode_UserGuide/Contents/Resources/en.lproj/Introduction/ Introduction.html
- 68. Xcode’s Interface Builder
- 69. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 70. No.4 Backup Anything impossible would be possible Backup your Artwork & Xcode projects
- 71. iPhone SDK Frameworks HTML CSS JavaScript Titanium PhoneGap http://www.appcelerator.com/ http://phonegap.com/ products/titanium-mobile/
- 72. iPhone SDK Frameworks MonoTouch Corona C# .NET Lua http://monotouch.net/ http://www.anscamobile.com/
- 73. 6 Major Types of Mockup / Prototype Paper Prototype Online Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 74. iPhone WebKit Frameworks jQTouch http://www.jqtouch.com/ CiUI iUI http://code.google.com/ http:/ code.google.com/ / p/ciui-dev/ p/iui/wiki/Introduction
- 75. Mockup / Prototype Business Developers Paper Prototype Paper Prototype Sketching iPhone SDK IDEs iPhone SDK Frameworks iPhone Webkit Frameworks
- 76. Rapid Prototyping Developers Paper Prototype (Fast) iPhone SDK IDEs (Drag & Drop)
- 77. Family Project Design App Prepare Assets Paper Online / Desktop Audio iPhone 3Gs Audacity aviary.com Swatch.app Images GIMP pixlr.com sumopaint.com picnik.com aviary.com
- 78. sumopaint.com Free Images http:/ /www.freephotosbank.com/ http://www.everystockphoto.com/ http://www.imageafter.com/
- 79. Testing Code on Device http://www.mobileorchard.com/iphone- development-provisioning/
- 80. $99 iPhone Developer Program Portal Vibration Location Manager Mail Application Map Application Safari Application Device Orientation Accelerometer Audio Performance Overall Performance
- 81. iPhone Developer 1. Add Device Program Portal 2. Xcode Organizer
- 82. iPhone Developer Program Portal 3. Create Developer Certificate 4. Add to Keychain
- 83. iPhone Developer Program Portal 5. Create Apple ID 6. Create Provisioning Profile
- 84. iPhone Developer Program Portal 7. Add Provisioning Profile to Xcode Organizer 8. Test Code
- 85. Case Study
- 86. A No.
- 87. B No.
- 88. C No.
- 89. Tell Me Which is Best & Why
- 90. myStarbucks Find a Starbucks Coffee Sep 16, 2009 Version 1.0 Aug 9, 2009 Version 2.0 Free $0.99 Go Grande - Find your nearest Starbucks Feb 6 2009 Version 1.0.0 $0.99
- 91. Q&A
Architecting iOS Project
Presentation Transcript
- 1. Architecting iOS Project Massimo Oliviero
- 2. Massimo Oliviero Freelance Software Developer web http://www.massimooliviero.net email massimo.oliviero@gmail.com slide http://www.slideshare.net/MassimoOliviero twitter @maxoly
- 3. Massimo Oliviero http://pragmamark.org/ La prima community di sviluppatori iOS e Mac OS X in Italia. https://www.facebook.com/groups/pragmamark/
- 4. Agenda ‣ Project, how to design Xcode project ‣ Application, how to design an iOS app ‣ Resources, links, books and videos
- 5. Source code Kimera A simple iOS application for educational purpose https://github.com/maxoly/Kimera
- 6. Project
- 7. Project ‣ Conventions, how to naming file and folders ‣ Structure, how make the foundation of the project ‣ Folders, how to organize files and folders
- 8. Conventions
- 9. Naming Conventions ‣ First establish a naming convention for all the things for file names, class names, project names, images, etc. ‣ Use Pascal Case for files, folders and class start with a capital letter i.e. Controllers, MyClass, BestAppEver, etc. ‣ Use Camel Case for methods, properties & variables start with a lowercase letter i.e setFirstName:, userPassword, etc. ‣ Avoid using of acronyms and abbreviations What the hell does it mean“usrPswdLbl”? Yuck!
- 10. Coding Conventions ‣ Choose your coding conventions & style there are ton of conventions out there ‣ K&R Style, or Allman Indent Style http://en.wikipedia.org/wiki/Indent_style ‣ Also read Coding Guidelines for Cocoa by Apple http://developer.apple.com/library/mac/#documentation/Cocoa/ Conceptual/CodingGuidelines/CodingGuidelines.html ‣ But most important, choose a convention and respect it the important thing is always be consistent in your project
- 11. Structure
- 12. Structure ‣ Create a specific workspace don’t let Xcode do it for you ‣ Setting up projects with correct name and prefix use simple word (only alphanumeric) and at least 3 chars for prefix ‣ Create a Build Automation to scripting common tasks to compiling source code or to deploy artifacts with one command
- 13. Structure ‣ Create a AdHoc and AppStore Build Configuration So you can handle configuration for different destination ‣ Configure Build Settings to improve quality i.e. you can enable Static Analyzer or Treat Warnings as Errors ‣ Manage third-part libraries with CocoaPods it reduces headaches of storing/managing 3rd party libraries
- 14. Workspace
- 15. Project Name & Prefix ‣ Choose a simple Program Name Only alphanumeric characters, avoid spaces ‣ Choose a right Class Prefix At least 3 chars, use product name's acronym ‣ Choose your Personal Prefix Use it in your Library Projects ‣ Use Automatic Reference Counting If app targets iOS 5.0 or above
- 16. Build Automation ‣ It’s the act of automating a wide variety of tasks you can use build tools like Ant, Maven, Make , CMake or Rake ‣ At least you must automate Compiling and Deploying compiling and deploying are the most common tasks for developer ‣ You can also automate Testing and Docs generation they are useful to use in combination with a Continuous Integration
- 17. AdHoc & AppStore Configuration ‣ Use different Configurations to specialize the behavior i.e. Code Signing Identity, Preprocessor Macros, Linker Flags, etc. ‣ Use AdHoc Configuration to deploy testing app i.e. app for TestFlight with its own Code Signing Identity & Linker Flags ‣ Use AppStore Configuration to deploy on App Store Duplicate Release Configuration to use the same optimizations
- 18. Build Settings ‣ Enable Run Static Analyzer run the Clang static analysis tool on source files ‣ Enable Treat Warning as Errors it causes all warnings to be treated as errors ‣ Disable Compress PNG Files instead use ImageOptim
- 19. CocoaPods ‣ Manage third-part libraries with CocoaPods download from http://cocoapods.org/ ‣ CocoaPods manage dependency for you it download source files, imports headers and configures flags ‣ It’s like Ruby Gem but for Objective-C! you can search pods, install & update with one command
- 20. Folders
- 21. Folders ‣ Put things in the right place ...and everything makes sense, unfortunately, Xcode doesn’t help us ‣ Map all Xcode group folder to file system directory Xcode group folder don’t represent physical folder ‣ Please remove Supporting Files group folder Who wants“Supporting Files”anymore? yuck!
- 22. My folders structure ‣ Application specific app related stuff like AppDelegate, main.m, .pch etc ‣ Controllers view (.xib) and view controller stuff put together (obviously) ‣ Library specific application classes like helpers, base classes, services, etc
- 23. My folder structure ‣ Models application domain models and entities, Core Data model too ‣ Resources assets like images, fonts, sounds, videos, etc. ‣ Vendors third part libraries and frameworks
- 24. Controllers ‣ Put .xib, .h and .m together in the same folders ‣ One (physical) folder for each view controller ‣ If there are too many, group them into a subfolder ‣ Group them by tab (TabBar) or by functions
- 25. Resources ‣ One folder for each type of asset images, fonts, sounds, videos, strings, plist, samples ‣ One subfolder for each type of image buttons, backgrounds, logos, shapes, icons, app (splash etc.) ‣ If your app support multiple themes, create a hierarchy themes > themes name > images, fonts, etc. ‣ Name image files based on state “button_blue_normal.png”,“button_blue_highlighted.png”, etc.
- 26. Application
- 27. Application ‣ Design, a quick recap to design principles and patterns ‣ Layers, how to organize your app classes ‣ Compositions, a group of reusable components ‣ Best Practices, a list of useful techniques
- 28. Design
- 29. Design ‣ Typically an application is divided into layers A layer is a black box with a contract that define an input and output ‣ To increase the cohesion and decoupling of the software The layers, if well designed, help to decouple and increase the cohesion ‣ Cohesion indicates strongly related software module it would be a subroutine, class or library with common responsibilities ‣ Coupling measure the level of dependency between two software module, such as classes, functions or library
- 30. Design Principles ‣ Single Responsibility Principle A module should have a single responsibility, and that responsibility should be entirely encapsulated by the module ‣ Open Closed Principle A module should be open for extension but closed for modifications ‣ Liskov’s Substitution Principle Derived types must be completely substitutable for their base types
- 31. Design Principles ‣ Interface Segregation Principle Clients should not be forced to depend upon interfaces that they don't use ‣ Dependency Inversion Principle High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions ‣ SOLID: the "first five principles" Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion
- 32. From Principles to Patterns ‣ Design Pattern is a general reusable solution to a commonly occurring problem within a given context ‣ It’s a description or template for how to solve a problem It’s not a finished design that can be transformed into source code ‣ There are many types of design patterns Architectural, Algorithm strategy, Computational, Implementation strategy, Structural, etc.
- 33. Most Common Design Patterns ‣ Model View Controller Design Pattern It’s a fundamental design pattern in Objective-C. ‣ Singleton Design Pattern For your information the AppDelegate is a singleton ‣ Chain Of Responsibility Design Pattern Have you ever met the Next Responder or the First Responder?
- 34. Layers
- 35. Layers ‣ Layer represents a logical section of the system Layer enforce reusability and testability ‣ A typical client/server app have at least 3 layers Presentation Layer, Business Layer and Data Access Layer
- 36. Layers Presentation Layer Data Access Layer Business Layer Views Controllers Service Layer Domain Model Layer Persistence Layer Network Layer
- 37. Presentation Layer
- 38. Presentation Layer ‣ It have 2 components: the UI and the presentation logic in Cocoa the UI is the View and the presentation logic is the Controller ‣ Cocoa adopt Model View Controller Design Pattern the Presentation Layer is already in iOS SDK out-of-the-box ‣ Advanced Appearance Customization with Theme user Appearance Proxy and Theme technique to customize UI.
- 39. Theme ‣ Create a @protocol that define a“theme” ‣ Implements @protocol in your theme class @protocol MGATheme <NSObject> - (void)themeLabel:(UILabel *)label type:(MGAThemeLabelType)type; - (void)themeButton:(UIButton *)button type:(MGAThemeButtonType)type; @end @interface MGABlueTheme : NSObject<MGATheme> @end @interface MGAMetalTheme : NSObject<MGATheme> @end
- 40. Presentation Layer Presentation Layer - (View Controller) UIView UIViewController Theme Model Appearance
- 41. Business Layer
- 42. Business Layer ‣ It holds the specific app Business Logic and Behaviors It is concerned with the retrieval, processing, transformation, and management of application data; application of business rules and policies ‣ The Domain Model is a conceptual model of business It describes the various entities, their attributes, roles, and relationships, plus the constraints that govern the problem domain ‣ Business Layer gets data through a Service Layer Service Layer defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation
- 43. Domain Model Layer ‣ Domain Model An object model of the domain that incorporates both behavior and data ‣ You can use simple Objective-C objects A plain old Objective-C object that inheriting from NSObject ‣ Or you can use Core Data objects you can extend the class NSMangedObject with your Objective-C class
- 44. Service Layer ‣ Service Layers is a design pattern The benefits a Service Layer provides is that it defines a common set of application operations available to different clients and coordinates the response in each operation. ‣ Service Layer uses Data Access Layer to access data Service Layer uses DAL to performs the task of retrieving and storing data both from server via network and from database ‣ Service Layer is used by ViewController No more a ton of line of codes in your ViewController, instead few lines of simple Service Layer calls
- 45. Data Access Layer
- 46. Data Access Layer ‣ It’s a layer which provides simplified access to data The data may be stored in a persistent storage like SQLite or in a backend accessible by network ‣ It may uses a Persistence Layer or Network Layer Both exposes a simplify contract to access data
- 47. Persistence Layer ‣ The persistence layer deals with persisting The persistence layer is responsible for manipulating the database, and it is used by the service layer ‣ You can use Core Data as Persistence Layer Or, in alternative, you can use FMDB for direct access to SQLite
- 48. Network Layer ‣ Network Layer is responsible of all networking calls ‣ You can use AFNetworking as Network Layer AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of NSURLConnection, NSOperation, and other familiar Foundation technologies
- 49. Composition
- 50. Composition ‣ It’s a way to combine objects into more complex ones Compositions are a critical building block of many basic data structures, including the tagged union, the linked list, and the binary tree, as well as the object used in object-oriented programming ‣ In a real-world app composition takes an important role On iOS / OS X App composition is necessary for a good layering and for a structure UI.
- 51. Composition - Custom Views ‣ Custom Views are an example of composition A custom view is used to manage small portions of the interface in order to recycle the content and its management ‣ In a real-world iOS/OS App there are many custom views For example, all views that must be inserted in a scroll view, or all those portions of the view that occur multiple times in different view and only with different content.
- 52. Best Practices
- 53. General Best Practice ‣ Use Automatic Reference Counting Always use ARC. All new code should be written using ARC, and all legacy code should be updated to use ARC ‣ Use AppDelegate as Singleton Create all common and singleton objects in App Delegate and then expose them by UIResponder Category
- 54. Coding Best Practice ‣ Create a property for every ivar and use self to access it Always create a @property for every data member and use“self.name” to access it throughout your class implementation ‣ Alway declare“atomic”or“nonatomic”attribute Always use the“nonatomic”attribute on your properties, unless you are writing a thread-safe class and actually need access to be atomic ‣ User literals and modern Objective-C syntactic sugar The source code will be less verbose and more clear.
- 55. Presentation Best Practice ‣ Create a base UIViewController Create a MYBaseViewController from which all the view controllers inherit. In this way all the controllers can inherit common behavior. ‣ Create a base UIView Create a MYBaseView from which all the custom views inherit. In this way all the views can inherit common style and appearance ‣ Create a base UITableViewCell Create a MYBaseTableViewCell from which all the custom table view cells inherit. In this way all the cells can inherit common style and appearance
- 56. Code Design Best Practice ‣ API Design Pay attention to the design of your API. Learn your target platform's conventions before coding. Define the rules that are in accordance with the convention of language ‣ Block and Delegation When should I use blocks instead of delegation for callbacks? Pay attention to this topic and alway look at Apple docs to see how they done
- 57. Resources
- 58. Links ‣ Blocks vs Delegation http://thejoeconwayblog.wordpress.com/2012/05/29/blocks-or- delegation/ ‣ API Design http://mattgemmell.com/2012/05/24/api-design/ ‣ Modern Objective-C http://www.slideshare.net/giuseppearici/modern-objectivec-pragma- night
- 59. Links ‣ objc.io - A periodical about best practices and advanced techniques in Objective-C http://www.objc.io/ ‣ Automatic Reference Counting http://www.slideshare.net/giuseppearici/pragma-night- automaticreferencecounting
- 60. Videos ‣ Customizing the Appearance of UIKit Controls Session 114 - WWDC 2011 Session Videos ‣ Advanced Appearance Customization on iOS Session 216 - WWDC 2012 Session Videos
- 61. Books ‣ Cocoa Design Patterns ‣ Erik M. Buck & Donald A. Yacktman ‣ Addison Wesley
- 62. Books ‣ Patterns Of Enterprise Application Architecture ‣ Martin Fowler ‣ Addison-Wesley Professional ‣ updates: http://martinfowler.com/ books/eaa.html
- 63. Thank you Massimo Oliviero massimo.oliviero@gmail.com http://www.massimooliviero.net follow me on twitter @maxoly http://www.slideshare.net/MassimoOliviero https://speakerdeck.com/massimooliviero
Thursday, 29 August 2013
Good Coding Practice Objective - C
Thanks to Mr: Jean-Luc David
Presentation Transcript
- 1. Agenda• Project Structure• Design Patterns & Architecture• Storing Data• Coding Conventions
- 2. What main design pattern doesApple recommend forstructuringyour iOS projects?
- 3. Model-View-Controller Controller Update Coordination Changes Changes Update Model Data View Display
- 4. Default Project • Notice Classes is a catch-all default ‘’bucket’’ for code
- 5. MVC Formatted Project• Remove references• Create class folders in Finder • AppDelegate • Controllers • Helpers • Models• Drag into Xcode
- 6. According to Apple, should themodel, view or controller be usedto capture events?
- 7. Roles & Responsibilities• Model • Data/Algorithms/Networking • Most of your custom code lives here• View • Display/Event Capture/Visual Appeal • Don’t try to reinvent UIKit, use it• Controller • Coordination/Delegation/Odd Jobs • Transitions, Startup/Shutdown
- 8. Is this a good pattern & why? Update
- 9. Don’t cut out the controller! Avoid bi-directional messaging Reject DelayValidate Update • Network Access • Multiple Choices • Commit
- 10. Is this a good pattern & why?
- 11. Loose Coupling• Don’t skip MVC layers when messaging • Use controllers to coordinate messages• Don’t mix MVC roles in one object • Don’t gather too much work in one place• Don’t declare data in your view classes • Maintenance nightmare • You can display data in a view, just don’t store it
- 12. What are three of the designpatterns used to communicatebetween the model, view &controller?
- 13. Communication Between Objects Target-Action Notification Delegation Reuse controls without Broadcast changes Control reuse subclassing “Yes” « When tapped, call this method » « Software keyboard “End Editing?”-setTarget:(id)target action:(SEL)action…about to appear! » UIKit (UIScrollView, ect) NSNotificationCenter Will/Did/Should -(void)scrollViewDidZoom:
- 14. How do you create a customcontroller to split the screen in twoparts?
- 15. You Don’t! Use the UISplitViewController• Don’t try to reinvent the wheel • UIKit has a lot of the base controls you need • Really question whether you need a custom control (and if it exists already)• Don’t misuse framework classes • ie Removing views from UIViewControllers• Don’t try to reinvent the way models, views & controllers talk to each other • Use delegates & notifications
- 16. Is this a good pattern & why?-(void)scrollViewDidScroll:(UIScrollView *)scrollView{ if ([scrollView isKindOfClass:[UITableView class]}){ // do something } else { // use UIScrollView logic}
- 17. Class checks in delegate methodsCode unmanagable over time - EverythingControllersCoding horror - iOS version of a GOTOCorrect Approach oniPadParcel out yourcontrollers
- 18. MANDATORY: ALWAYS write/model out your iOS app design before coding!At first, I was like… But then, it was like… (in your brain) (in the repo)
- 19. Creating an MVC diagram of your project• Means you thought through the architecture• Means you know how the code will be organized physically & logically• Means you potentially avoided structural bugs• Easier to validate with the team• High quality projects & happy clients
- 20. What’s the optimal architecture fora Universal Application?
- 21. Optimal Universal App Architecture iPhone App iPad App UI Framework (Views & Controllers) Non-UI Framework (Networking & Models)
- 22. Photo Sharing Application Data from the model is in both the inspector and in the toolbar
- 23. MVC Structure Update Change Change Update
- 24. What are the six primary ways ofstoring data on iOS?
- 25. Six Model Options• Property Lists• Archives• Custom Files• Server/iCloud/APIs• SQLite• CoreData
- 26. According to Apple, what data shouldyou store in your AppDefaults/Preferences?
- 27. Don’t store data in settings!• Wrong tool for the job• App may get rejected• Settings Panel test • On/Off Advanced Features
- 28. What should you use for quick storageofstrings, numbers, arrays, dictionaries, ect?
- 29. Property Lists.
- 30. What should you use to store partialgraphs?
- 31. CoreData• Modeling Tools• Simple save/restore• Queries• Data Protection• Ordered Relationships• UIManagedDocument• Partial Graphs• Undo• Incremental Stores• ect…
- 32. What should you use to include datawith queue-based concurrency in yourapp?
- 33. CoreData again.
- 34. What should you use if you are dealingwith a lot of legacy code or data, or youneed to create an NSObject-basedgraph?
- 35. Custom Files.
- 36. When would you want to use a dataarchive?
- 37. For easily « serializing »and « deserializing »objects in a data file.
- 38. What are the two primary features ofSQLite?
- 39. Provides Database functionality for iOS appsSupports Object Relational Mapping
- 40. Know Your Data Model Options• Property Lists• Archives• Custom Files• Server/iCloud/APIs• SQLite• CoreData
- 41. Coding Conventions • Brace style for if-else • Parenthesis style • Leading underscores • Code indenting • CapitalizationStyle (ie capitalization_style) Check out the Google iOS Style guide & Apple docs: http://google- styleguide.googlecode.com/svn/trunk/objcguide .xml
- 42. What is KVO?
- 43. Key-Value Observing (KVO) • Requires your code to be compliant • Follow style guide • Instrument your own notifications • Automatic Change Notifications for your objects
Battery status
BatteryStatus
- Documentation
========================================================================
DESCRIPTION:
Demonstrates the use of the battery status properties and notifications provided via the iPhone OS SDK.
Testing:
The sample is only useful when run on a device. The simulator always returns unknown battery status.
========================================================================
BUILD REQUIREMENTS:
iOS 4.0 SDK
========================================================================
RUNTIME REQUIREMENTS:
iOS 3.2 or later
========================================================================
PACKAGING LIST:
BatteryStatusAppDelegate
Delegate of the main application that presents the initial window.
RootViewController
Controller for initial window. Receives battery status change notifications. Queries the
battery status and presents it in a UITableView. Enables and disables battery status updates.
========================================================================
CHANGES FROM PREVIOUS VERSIONS:
Version 1.1
Updated for iOS 4.
Version 1.0
First release.
Copyright (c) 2009-2010 Apple Inc. All rights reserved.
- Design
- Code
RootViewController.h
@interface RootViewController : UITableViewController
{
@private
/* private formatter instance that we'll re-use */
NSNumberFormatter *numberFormatter;
}
@property (nonatomic, retain, readonly) NSNumberFormatter *numberFormatter;
@end
------------------------------------------------------------
RootViewController.m
#import "RootViewController.h"
@implementation RootViewController
enum ControlTableSections
{
kMonitoringSection = 0,
kLevelSection,
kBatteryStateSection
};
- (void)dealloc
{
[numberFormatter release];
[super dealloc];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// This title will appear in the navigation bar
self.title = NSLocalizedString(@"Battery Status", @"");
// Register for battery level and state change notifications.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryLevelDidChange:)
name:UIDeviceBatteryLevelDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(batteryStateDidChange:)
name:UIDeviceBatteryStateDidChangeNotification object:nil];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
- (NSNumberFormatter *)numberFormatter
{
if (numberFormatter == nil)
{
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterPercentStyle];
[numberFormatter setMaximumFractionDigits:1];
}
return numberFormatter;
}
#pragma mark - Switch action handler
- (void)switchAction:(id)sender
{
if ([sender isOn])
{
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
// The UI will be updated as a result of the first notification.
}
else {
[UIDevice currentDevice].batteryMonitoringEnabled = NO;
[self.tableView reloadData];
}
}
#pragma mark - Battery notifications
- (void)batteryLevelDidChange:(NSNotification *)notification
{
[self.tableView reloadData];
}
- (void)batteryStateDidChange:(NSNotification *)notification
{
[self.tableView reloadData];
}
#pragma mark - UITableView delegates
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 3;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *title = nil;
switch (section)
{
case kBatteryStateSection:
{
title = NSLocalizedString(@"Battery State", @"");
break;
}
}
return title;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rowCount = 1;
if (section == kBatteryStateSection)
{
rowCount = 4;
}
return rowCount;
}
static NSInteger kLevelTag = 2;
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kMonitoringCellIdentifier = @"Monitoring";
static NSString *kLevelCellIdentifier = @"Level";
static NSString *kStateCellIdentifier = @"State";
UITableViewCell *cell = nil;
switch (indexPath.section)
{
case kMonitoringSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kMonitoringCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kMonitoringCellIdentifier] autorelease];
cell.textLabel.text = NSLocalizedString(@"Monitoring", @"");
UISwitch *switchCtl = [[[UISwitch alloc] initWithFrame:CGRectMake(197, 8, 94, 27)] autorelease];
[switchCtl addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventValueChanged];
switchCtl.backgroundColor = [UIColor clearColor];
[cell.contentView addSubview:switchCtl];
}
break;
}
case kLevelSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kLevelCellIdentifier];
UILabel *levelLabel = nil;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kLevelCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = NSLocalizedString(@"Level", @"");
levelLabel = [[[UILabel alloc] initWithFrame:CGRectMake(171, 11, 120, 21)] autorelease];
levelLabel.tag = kLevelTag;
levelLabel.textAlignment = UITextAlignmentRight;
[cell.contentView addSubview:levelLabel];
levelLabel.backgroundColor = [UIColor clearColor];
}
else {
levelLabel = (UILabel *) [cell.contentView viewWithTag:kLevelTag];
}
float batteryLevel = [UIDevice currentDevice].batteryLevel;
if (batteryLevel < 0.0)
{
// -1.0 means battery state is UIDeviceBatteryStateUnknown
levelLabel.text = NSLocalizedString(@"Unknown", @"");
}
else {
NSNumber *levelObj = [NSNumber numberWithFloat:batteryLevel];
// Using the numberFormatter property lazily creates that object the
// first time it's used.
levelLabel.text = [self.numberFormatter stringFromNumber:levelObj];
}
break;
}
case kBatteryStateSection:
{
cell = [tableView dequeueReusableCellWithIdentifier:kStateCellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kStateCellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"StatusClear.png"]] autorelease];
}
switch (indexPath.row)
{
case 0:
{
cell.textLabel.text = NSLocalizedString(@"Unknown", @"");
break;
}
case 1:
{
cell.textLabel.text = NSLocalizedString(@"Unplugged", @"");
break;
}
case 2:
{
cell.textLabel.text = NSLocalizedString(@"Charging", @"");
break;
}
case 3:
{
cell.textLabel.text = NSLocalizedString(@"Full", @"");
break;
}
}
UIImageView *statusImageView = (UIImageView *) cell.accessoryView;
if (indexPath.row + UIDeviceBatteryStateUnknown == [UIDevice currentDevice].batteryState)
{
statusImageView.image = [UIImage imageNamed:@"StatusGreen.png"];
}
else {
statusImageView.image = [UIImage imageNamed:@"StatusClear.png"];
}
break;
}
}
// Set attributes common to all cell types.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
@end
------------------------------------------------------------
BatteryStatusAppDelegate.h
@interface BatteryStatusAppDelegate : NSObject <UIApplicationDelegate>
{
UIWindow *window;
UINavigationController *navigationController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
@end
------------------------------------------------------------
BatteryStatusAppDelegate.m
#import "BatteryStatusAppDelegate.h"
#import "RootViewController.h"
@implementation BatteryStatusAppDelegate
@synthesize window;
@synthesize navigationController;
#pragma mark -
#pragma mark Application lifecycle
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Save data if appropriate
}
#pragma mark -
#pragma mark Memory management
- (void)dealloc {
[navigationController release];
[window release];
[super dealloc];
}
@end
------------------------------------------------------------
Copyright (C) 2010 Apple Inc. All Rights Reserved.
Subscribe to:
Posts (Atom)