Monday, August 27, 2012


IOS Basics

 Welcome to the blog for ios dummies.I wrote some of the ios interview questions and basics.

IOS Definitions

  • id : The id type means that object variable can refer to any kind of object.The objects and classes it implements are not known when you compile the app
 
  • #import derivative guards against including a single file multiple times

  • property is an objective C directive that allows to generate accessors.here we can specify the name and type of the property

  • @synthesize directive automatically generates setters and getters for us

  • interface : the interface of class is usually stored in .h file and defines instance variables and public methods

  • implementation : The implementation of a class is in .m file and usually contains the actual code of the methods

  • - sign ->instance methods + sign -> class methods
                 We need to create an instance to use instance methods whereas class methods are functions which class offers without creating object from that class
        MyClass *object;    [object instanceMethod];
        [MyClass classMethod];

  • dealloc : The dealloc method is called on an object when it is being removed from memory

  • category : Category allows you to add methods to an existing class without sub-classing it.For example we can create category for NSObject that allow to add methods for NSObject class
            @interface NSObject (Utilities) {
                BOOL isUrl;
            }
            @implementation NSObject (Utilities)
            -(BOOL)isUrl{
               
            }
            NSObject *object = anObject;
            if ([object isUrl]) {
           
            }
Unlike sub-classing, categories cant add instance variables

  • protocol : Protocols are used to define methods that are to be implemented by other classes.For example we can implement cellForRowatIndexPath method to ask for cell content to insert in tableview.This method is defined in UITableViewDataSource protocol
        @protocol MyTestProtocol <NSObject> {
            -(void)methodSuccess;
        }

  • delegate : Delegate is an object which receives messages from another object.

  • frame - bounds : frame of a rectangle is represented relative to its superview it is contained in.bounds  of a rectangle is represented relative to its own coordinate system

  • AppDelegate - ViewController : AppDelegate is responsible for the life cycle of the application like what to do when the user presses the home button, exits the app, enter the background etc.,ViewController is responsible for the connection between model and view

  • UIButton -> UIControl -> UIView -> UIResponder -> NSObject

  • There are no radio or check buttons in ios.Adding radio or check button images to UIButton will make the similar effect

  • singleton : singletons are used to keep only one object of a class in existence for the entire lifecycle of application

Property attributes
  • assign : We can use this attribute for non-pointer attributes like bool, int, float
  • retain , copy :  retain and copy increases the retain count.When we use retain, it simply increases the retain count, but when we use copy, a separate copy of object is created.copy is needed when an object is mutable.if u need the value of the object and if you dont want to reflect any changes made by other owners, we will use copy.
  • atomic - nonatomic : With atomic, the synthesized setters/getters will ensure that whole value is returned from getter/setter irrespective of thread they are running.In nonatomic, there is no such guarantee.If multiple threads try to change or read the property , bad things may happen.non-atomic is faster.atomic is default and read/write are thread safe.
  • readwrite - readonly : readwrite is default.When u synthesize, both setters and getters will be created.If we use readonly,no setter will be created.Use it for a value if u dont want to change after initializing the object


    Memory management in Objective C

  • Automatic garbage collection
  • Reference counting
  • ARC
   
    Garbage Collection : In Automatic garbage collection, a separate chunk of code runs in the background to see what objects are being referenced and which ones are not needed.It then deletes any unused objects automatically.In objective c-2.0, there is option to enable automatic garbage collection.It is not available in ios development

    Reference Counting : The basic principle in memory management is : When u own an object either by creating it or by adding ownership, u are responsible to release it.When you dont own an object, you must not release it.You can own an object either by using alloc, copy or retain.And we can use release to remove it from memory.
    Each object has a retain count which increases by calling retain and decreases by calling release.When retain count equals 0, the object is released and the memory is used for something else.
    When an objects retain count drops to zero, the runtime calls the dealloc method of the object class before destroying it to free any resources that object holds.
    We can autorelease objects.With this retain count isnt decreased immediately, but is decreased when the autorelease pool is drained.iOS apps have an event loop in which the code runs.After each iteration of the event loop, autorelease pool is drained
    drain releases AutoReleasePool..There is no difference between drain and release unless you use automatic garbage collection

ARC : In ARC, we dont need to worry of memory management, the system will take care of it.The system also uses the same reference counting mechanism but it inserts the appropriate memory management calls during compile time


Application Life Cycle on iOS

 After tapping the application, it proceeds to launch by calling the main () function.After that the initialization work is handed over to UIKit which loads the applications user interface and calls its event loop.
    UIKit sends messages to third party applications delegate object to let it know what is happening.In iOS 4 and later , third party applications remain resident in memory after they are quit, so that subsequent launches of the application may not involve starting of the application from scratch
    Different application states in ios4 :
  • Not Running : The application has not been launched
  • InActive : The application is running in background but not receiving events
  • Active : The application is running in foreground and receiving events
  • Background : Most applications enter this state on their way being to suspended state
  • Suspended : The application is in background and not executing code


Modal-View-Controller Pattern

    The model contains the data, view displays the information contained in the model and controller is responsible for accessing data from the model and displaying in the view
    For example a Book object contains information related to book like number of pages, title of book etc.,View could display the list of Books and book information.But the view doesnot obtain information directly from model, it uses the controller as mediator which instructs it when and what to display


Instruments

Instruments is a preformance, analysing and testing tool for dynamically tracing and analysing ios code
Different kinds of instruments are used for better app development.
  • Static Analyzer : XCode has built in static analyzer.This works like a compiler and looks for any logic flaws.This helps in uncutting down any unused variables and some memory mangament issues

  • Allocations Instrument : Allocations instrument is used to take snapshots of the heap as app performs the task.Using this we can identify the situations where the memory is lost.By taking the snapshot of the heap we can see the difference in memory for a particular test scenario

  • Leaks Instrument : Leaks instrument will look for situations where memory has been allocated and we are no longer able to use that memory

  • Zombie Instrument : Zombie Instrument provides scenarios where memory is allocated and released before the app is done using it.This scenarios are difficult to track using debugger.The Zombie instrument keeps empty or dead objects alive in place of objects already released.These objects are later accessed by faulty application logic and halt the execution of the app instead of crashing

  • Time Profiler Instrument : This instrument illustrates how much time is spent on each code segment.This instrument is recommended to use for devices because performance will vary from simulator and device


XML Parser for iOS

There are two types of parsers: SAX parser or DOM parser
    Using SAX parser, the code is notified as the parser walks through the xml tree whereas DOM parser reads the entire document and builds in-memory representation to query different elements.
    • NSXMLParser is a SAX parser and readonly
    • KissXML, TouchXml are DOM parsers
    • libxml provides two types of parsers SAX and DOM
    • To read small documents where performance doesnt matter use TouchXML or KissXML but to read/write small documents KissXML is a better option
    • To read large documents, use libxml SAX or libxml DOM
    • If u are dealing with small documents and if u are not interested in adding third party libraries use NSXML   

Push Notifications

 Push notifications are used to display remote messages.First the app needs to enable push notifications.Then the app receives device token.This is the place where the notifications will be sent to.The app sends the device token to your server.Then the server sends push notifications to APNS(Apple Push Notification Service).APNS sends notications to device token
    When the device receives push notifications, it displays an alert, play sound or update the badge.
    To add push notifications to the app, we need to sign in with provisional certificate that is configured for push


Provisioning Portal
There are two portals to use while developing apps to ios:
      • iOS Provisioning Portal
      • iTunes Connect
    Apps installed from app store comes bundled with signed Apple certificate which the system verifies before it allows the app to run.If the signature is not valid, the app wont run

iOS Provisioning Portal allows to generate profiles that allow XCode to sign the apps for the device to identify.Here also we have two profiles.Development profiles are tied to specific devices so the app can run only on those devices.Distribution profiles are used to sign the apps before submitting to apple for approval.We cant use them to install apps on devices because apple still has to sign the app for approval.It also generates Push Cerificates in case app wants to send push notifications

iTunes Connect is the portal where we will send the app to appstore.Here we will register a new app, add screenshots, pricing, enabling game center etc.,

Generating Provisional Profile:
    First from Keychain access menu, request a certificate from a certificate authority and save this to disk.Upload this in the developement certificates section of provisional portal and download cer file.Double-click to install it.Download AppleWWDRCA.cer and double-click to install it.It will open keychain access.

Next step is to register the device by adding  the UDID of the device.we can get udid through organiser ar through iTunes.
Next step is to register the app Id.every app needs its own app id.App id is a combination of 10 character seed prefix generated by apple and a bundle identifier created by you.Apple recommends to use reverse domain name style string for bundle identifier(com.geodesic.enlytenote).App Id is created by filling the app name, seed id and bundle identifier
    Finally Provisioning Profile is created by adding profile name, certificate from certificates section, app id you created and devices you want to use to test your app.

The same process is repeated for distribution profile.Go to distribution tab in provisional portal and add distribution certificate generated from certificates section and same process is repeated and generate distribution provisional profile

KeyChain Access:  A Keychain is an encrypted container that holds passwords for multiple applications and security services