Showing posts with label Objective C. Show all posts
Showing posts with label Objective C. Show all posts

Constructs in Objective C and Swift

Classes, Structs and Enums are called Constructs and all three of them allow your program to store, organize or manipulate data in different ways with different capabilities.

Classes
  • General Purpose, flexible construct that becomes the building blocks of your program code.
  • Have properties and methods that provide data storage and functionality to constructs
  • Can use inheritance
  • Can use initializers and de-initializers when setup or tear down when they are created or destroyed.
Structs
  • Structs in Swift can have Properties and Methods (Swift Only)
  • Can use initializers (Swift Only)
  • No Inheritance
  • Passed by copy ( this can be advantage/disadvantage based on the needs)
Enums:
  • Way to group related elements
  • Can include functions (Swift only)
  • Can use initializers (Swift only)

Operators in Objective C and Swift

Common for Objective C and Swift
  • Assignment Operator ( = )
  • Arithmetic Operator
    • addition +,
    • Subtraction -, 
    • Multiplication *,  
    • Division /
  • Remainder (Modulo) Operator %
  • Unary plus operator (+), Unary minus operator (-), unary operator is prepended directly on the value it operates on.
  • compound assignment/short hand operators (x+=y, x-=y, x*=y, x/=y, x%=y, x&=y, x|=y, x^=y)
  • Increment (++) & decrement operator (—) {int x=9, int y: y= ++x , y = - - x } (Removed in Swift 3)
  • Relational/Comparison operators 
    • Equal to (a == b)
    • Not equal to (a != b)
    • Greater than (a > b)
    • Less than (a < b)
    • Greater than or equal to (a >= b)
    • Less than or equal to (a <=  b)
  • Logical Operator 
    • Logical Not (!a)
    • Logical AND (a && b)
    • Logical OR (a || b)
  • Ternary Conditional Operator ( if condition? expression 1 : expression 2 )
Swift Only
  • Range Operator 
    • Closed Range Operator '1…10', includes 1 and 10 in this range.
    • Half Open Range Operator '1..~10 , includes 1 but not 10
  • Nil-Coalescing Operator (x??y)
The nil-coalescing operator (x ?? y) unwraps an optional x if it contains a value, or returns a default value y if x is nil. The expression a is always of an optional type. The expression y must match the type that is stored inside x.

The nil Coalescing operator is shorthand for the below code:

x != nil ? x! : y

The code above uses the ternary conditional operator and forced unwrapping (x!) to access the value wrapped inside a when x is not nil, and to return x otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

Pointers

In Objective C all objects are referenced using pointers:

A pointer is a variable which stores memory address instead of value itself.

how big is int, 4 bytes
how big is char, 1 byte
how big is String, image or video?  we often don’t know and it might even change during our program so we need more flexible way to manage objects and pointers are one way of allowing us to do that.

Using pointers allows us to pass around the objects (just by passing around the address of object) without having need to copy them which is time consuming and inefficient  

E.g.   NSString* welcomeString;
         NSDate* todayDate;

welcomeString = @“Welcome to Objective C”;

Here the string 'Welcome to Objective C’ string is not directly stored in ‘welcomeString’ instead the address/memory location of 'Welcome to Objective C' is stored in ‘welcomeString which is contrary to 'int highScore = 100’ where ‘highScore’ variable directly stores value. ( this is because objects are more complex than primitive types)

if you want to make and use of simple object, we need pointers to reference them.
Note: Explicit use of pointers in Swift is not required unlike Objective C. e.g let someInstance = SomeClass ( ) whereas in objective C it is SomeClass *someInstance = [SomeClass alloc] init];

Structures in Objective C and Swift

Structure is a complex data type which contains individual elements which defer in type. 
There are many situations in programming where discrete types have to be identified together as one unit. In this situations we make use of Struct.

Structs are used to represent a record, Suppose you want to keep track of your books in a Library. you might want to track the following attributes about each book.

Struct Book {
Title
Author 
Subject
Book ID
};

Struck Person {
Name
Age
Height
Weight
Gender
Color
};

Individual elements of Struct are referred to as members

Unlike Objective C, classes in Swift, structures can have methods, properties, initializers, and conform to protocols. The main difference between classes and structures is that classes are passed by reference, while structs are passed by value.

Set vs Array

The main difference is that NSArray is an ordered collection and NSSet is an unordered list of unique elements.

Set
  • Primarily access items by comparison   
E.g    let ingredients = [“Tea Powder”, “Sugar”, “Hot Water”, “Milk”, "Cardamom"]
          if ingredients.contains(“Cardamom”) {
print(“It is Cardamom Tea”)
}
  • unordered
  • does not allow duplicates
Array

  • Can access items by Index
  • Ordered
  • Allow duplicates

Dynamic Typing & Dynamic Binding:

Dynamic Typing in Objective C means that the class of an object type id is unknown at the compile time and is discovered at the run time based on the message sent to the Object.

Dynamic typing allows us to declare a variable that is capable of storing any type of object regardless of its class origin, this is achieved using the Objective C id type, the id type is a special, general purpose data type that can be assigned an object of any type.

Dynamic binding takes this one step further by allowing methods on object type id to be called without prior knowledge of the type of an object currently assigned to the variable.


Which object is create by UIApplicationMain function at app launch time?

The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.

How main function of an app gets called during the app launch cycle?

During app launching, the system creates a main thread for the app and calls the app’s main function on that main thread. The Xcode project's default main function hands over control to the UIKit framework, which takes care of initializing the app before it is run.

Name the application thread from where UIKit classes should be used?

UIKit classes should be used only from an application’s main thread.  Note: The derived classes of UIResponder and the classes which manipulate application’s user interface should be used from application’s main thread.

Does iOS support multitasking?

iOS 4 and above supports multi-tasking and allows apps to remain in the background until they are launched again or until they are terminated

Frame, Bounds and center in IOS?


Frame A view's frame (CGRect) is the position of its rectangle in the superview's coordinate system. By default it starts at the top left.
Bounds A view's bounds (CGRect) expresses a view rectangle in its own coordinate system.
Center A center is a CGPoint expressed in terms of the superview's coordinate system and it determines the position of the exact center point of the view.

How to make a NSURL Request and parse the XML response?


   
#import "ViewController.h"
#import "XMLReader.h"


      
     //first you need to create a URL using String.
      NSURL *url = [NSURL URLWithString:@"feed://feeds.feedburner.com/blogspot/MKGLf?format=xml"];
           
      //Once you create a URL,you are ready make a request.
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
       //After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and initialize them with NULL.
        NSURLResponse *response = NULL;
NSError *requestError = NULL;
      //Once you have response with you, capture your responseData using NSData.
       NSData *responseData = [NSURLConnection sendSynchronousRequest:request        returningResponse:&response error:&requestError];

        //Convert the response data into response String.
NSString *responseString  = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

        //Now you can start parsing the data using XML parser. You need XML parser in-order to     use the below class method "dictionaryForXMLString"
NSError *parserError = NULL;

      
NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL]; 

        //Once You have xmlDict handy, you can pass this to the any ViewController(like tableview) to populate the data.

       

What is the difference between the Release and Autorelease?

Release and Autorelease are the terms related to the Memory Management. whenever you own a object its your responsibility to release it . if you don't release it properly, Objective -C cannot reclaim it for the use of other objects and there will be a memory leak.

                                                        Different ways to own a object are alloc, new , retain and copy Whenever you use this things try to release it so Objective C will take care blowing that object. If you are not sure about releasing that object,  please make sure you do autorelease.

                                                         Whenever you do autorelease of an object the object is not released right way,  it will be added to the Autoreleasepool in the main function. The Autoreleasepool in the main function will maintain a stack of objects to be released and they are released one by  one when "drain"method is called eg: [pool drain]. Drain method is called repeatedly at the end of every event loop.

what is the event loop?

For instance when you click on the button  in the application, button goes and performs what needs to done and comes back to the normal state of the app this is considered as one event loop.

What is Retain Count or Reference Counting?

Retain Count is the term which is related to the Memory Management . whenever you create a object, Objective C doesn't really care about the object you have created , the area of memory is claimed for this object and retain count is increased by one.

                     YourClass *yourObj  = [ YourClass alloc] init];
                      ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
                      [obj someMethod];
                        [yourObj release];

whenever you release that object the retain count does  go down by one ,whenever the retain count reaches zero, Objective C blows that object and it will be ready to reclaim that memory for another Object.
                 
                   YourClass *yourObj  = [ YourClass alloc] init];
                   [someOtherObj someMethod];
                   [yourObj release];
                 
whenever you pass  "yourObj" to  someMethod of someOtherObj, then a retain message is passed to that object and retain count increased to two. someOtherObj will take care of reducing the retain count to one when it is done and the regular release that you made will reduce it to zero.

Here "yourObj" is the pointer variable that stores the memory address of the object (or) simply it is reference to the object. Even after the object is blown from the memory address of the memory still present in "yourObj" variable called dangling pointer but it refers to the nil object.

if you want to learn about what happens when you pass a message to nil Object, you can follow this link


What is Memory Management in Objective C?

Objective C wants you to manage memory for every Object you create, you don't have to do this with ints, chars, floats and bools but just objects. it doesn't matters whether those object are coming from your classes (or) frameworks. whenever you own a object by doing alloc, new, copy and retain you should make sure that its your responsibility to release that Object.

                      In many languages like Java, C#, ruby, python etc you just make the variables you need and language itself takes care of cleaning up the stuff. This is usually done by the part of the language named Garbage Collector. Even Objective C has kind of garbage collector but wasn't actually part of the language, they just added couple of years back. Garbage collector can't be used on iPhone , iPad and mac prior to Leopard so if you have to write code for those you have to do manually.

                      Garbage collection is never default in Object C, you have to choose and change the settings in the project you are working and often write code to opt into garbage collector. To even use Garbage collection you have to understand the manual memory management

For more information on how we can manage memory in different ways read Difference between Release and Autorelease

What is the difference between NSArray and NSMutableArray?

Regular NSArray is Immutable , i,e  whenever you create an NSArray object and initialize some values to that and later sometime in the project if u have to add some value or object to that instance of an array it won't let u do that.

NSArray *myArray = [NSArray arrayWithObjects: @"1", @"two", @"3", nil];

Here unlike the C-style Arrays you don't explicitly declare the size of an array, it will automatically does it until it hits nil.
The problem here is, sometime later if u want to add or remove object , you will not be able to do with the regular arrays. NSMutableArray which is the subclass of NSArray does this for you.

NSMutableArray *myArray = [NSArray arrayWithObjects: @"1", @"two", @"3", nil];

sometime later  if you want to add a string or object to this array, there are methods in NSMutableArray which lets you to do this.

[myArray addObject: @"four"];
[myArray removeObjectAtIndex:2];

What is the advantage of Arrays in objective C over C-style Arrays

We all know that an Array is the ability of a variable to hold the multiple values at the same time. Objective C supports C-Style way of doing the things and also has its own way which is much better than C.

First Lets talk about the C-style way of playing with  single values  and arrays.

C-style single value declaration and assigning
    
       int singleValue;    
       singleValue = 10; ( the value is stored in the variable named singleValue)

In this case Objective C  claims the memory space that can hold the SingValue and the max it can spare is 4 bytes since we are using int has a datatype.

C-style Arrays

      int multipleValues[3] ;

So here Objective C  claims the memory space that can hold 3 values  and each of 4 bytes maximum. Now you can start assigning values, you have to start from index 0 since in C and Objective C arrays are  Zero based.

         multipleValues[0] = 23;
         multipleValues[1] = 13;
         multipleValues[2] = 34;

or    
    
         multipleValues[3] = {23, 13, 34}

So what if you need to add an element to that array  in the future?

          multipleValues[3] = {23, 13, 34, 77}
Objective C will warn you that you have an excess element in array initializer. This limitation of fixed width is overcome'd in Objective C.

So what if you need to to access the element that you did't claim it before.

          multipleValue[55] = 88;

When you run this, it still works fine so there is no bound checking is done. This works better in Objective C way of doing the thing with NSArray.

So what if you need to mix the types in arrays like ints, floats and bool . C-style of doing the things doesn't let u do that but Objective classes which are added on top of C like NSArray will allow you to do all these things.

Does Objective C supports Multiple Inheritance?

The answer is NO. Objective C has the single Inheritance, all its behavior is inherited from the single super or parent class called NSObject.