Top 35+ Objective-C Interview Questions & Answers [ FRESHERS ]
Last updated on 04th Jul 2020, Blog, Interview Questions
Objective C is a programming language which was developed in 1980. It can be said as a general purpose object-oriented programming language which adds Small talk style messaging to C programming. This is mainly famous as this was the main language which was used by Apple for building macOS and iOS operating systems. Later it was also selected as the main language which was to be used by NeXT. Below are a few questions which can be asked in an interview on objective C.
1) Explain what is protocol in Objective-C.
A protocol declares a programmatic interface that any class may choose to implement. Protocols make it possible for two classes distantly related by inheritance to communicate with each other to accomplish a certain goal.
2) Explain types of protocol.
A formal protocol declares a list of methods that client classes are expected to implement. Formal protocols have their own declaration, adoption, and type-checking syntax. You can designate methods whose implementation is required or optional with the @required and @optional keywords. Subclasses inherit formal protocols adopted by their ancestors. A formal protocol can also adopt other protocols. Formal protocols are an extension to the Objective-C language.
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
3) Explain what is #import.
#import ensures that a file is only ever included once so that you never have a problem with recursive includes.
4) What is the difference between #import and #include in Objective-C?
import is super set of include, it make sure file is included only once. this save you from recursive inclusion. about “” and <>. “” search in local directory and <> is use for system files.
5) What is the use of category in Objective-C?
You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. You can also use categories of your own classes to: Distribute the implementation of your own classes into separate source files — for example, you could group the methods of a large class into several categories and put each category in a different file. Declare private methods.
- #import “SystemClass.h”
- @interface SystemClass (CategoryName)
- // method declarations
6) Limitations and problems with category?
Advantages: You can extend any class, even those, for which you do not have the source. Look, for example, into the UI extensions added by Apple to the NSString class for rendering, getting the metrics, etc. Since you have access to all instance variables, categories provide you with a nice way to structure your code across compilation units using logical grouping instead of the “it must all be in one phyiscal place” approach taken, for example, by Java. Disadvantages: You cannot safely override methods already defined by the class itself or another category.
7) Explain when to use NSArray and NSMutableArray. Which one is faster and threadsafe?
NSArray and its subclass NSMutableArray manage ordered collections of objects called arrays. NSArray creates static arrays, and NSMutableArray creates dynamic arrays
8) What is fast enumeration?
The object is usually a collection such as an array or set Several Cocoa classes, including the collection classes, adopt the NSFastEnumeration protocol. You use it to retrieve elements held by an instance using a syntax similar to that of a standard C for loop, as illustrated in the following example:
- NSArray *anArray = // get an array;
- for (id element in anArray)
- /* code that acts on the element */
9) Explain what is @synthesize in Objective-C
@synthesize creates a getter and a setter for the variable. This lets you specify some attributes for your variables and when you @synthesize that property to the variable you generate the getter and setter for the variable.
10) Explain how to call function in Objective-C.
Calling the method is like this [className methodName] however if you want to call the method in the same class you can use self [self methodName]
11) Explain what is dot notation
The dot syntax is just a shortcut for calling getters and setters, that is:
[foo length] and foo.length are exactly the same, as are:
[foo setLength: 5]
foo.length = 5
12) Mention whether NSObject is a parent class or derived class.
Objective-C defines a root class from which the vast majority of other classes inherit, called NSObject. When one object encounters another object, it expects to be able to interact using at least the basic behavior defined by the NSObject class description.
13) Explain the difference between atomic and nonatomic synthesized properties.
Atomic is the default behavior will ensure the present process is completed by the CPU, before another process accesses the variable is not fast, as it ensures the process is completed entirely
Non-Atomic is NOT the default behavior faster (for synthesized code, that is, for variables created using @property and @synthesize) not thread-safe may result in unexpected behavior, when two different process access the same variable at the same time.
14) What is GCD? What are advantages over NSThread?
GrandcentralDispatch: Because your device only has one processor, GCD probably only creates one thread for executing blocks and your blocks execute sequentially. You’ve created 10 different threads, though, and those each get a little piece of the available processing time. Fortunately, sleeping isn’t very processor-intensive, so all your threads run together pretty well. Try a similar test on a machine with 4 or 8 processing cores, and you’ll see GCD run more of your blocks in parallel.
The nice thing about GCD isn’t that it necessarily offers better performance than threads, it’s that the programmer doesn’t have to think about creating threads or matching the number of threads to the number of available processors. You can create lots of little tasks that will execute as a processor becomes available and let the system schedule those tasks for you.
15) What is KVC and KVO? Give an example of using KVC to set value.
Key-Value-Coding (KVC) means accessing a property or value using a string. id someValue = [myObjectValueForKeyPath:@”foo.bar.baz”];
Which could be the same as:
- id someValue = [[[myObject foo] bar] baz];
Key-Value-Observing (KVO) allows you to observe changes to a property or value.
To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.
[myObject addObserver:self forKeyPath:@”foo.bar.baz” options:0 context:NULL];
16) What are blocks and how are they used?
Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values.
The syntax to define a block literal uses the caret symbol (^), like this:
- NSLog(@”This is a block”);
17) What is responder chain?
The responder chain is a series of linked responder objects. It starts with the first responder and end with the app object. If the first responder cannot handle an event, it forwards the event to the next responder in the responder chain.
18) What is id?
id is a pointer to any type, but unlike void * it always points to an Objective-C object. For example, you can add anything of type id to an NSArray, but those objects must respond to retain and release .
19) What is instanceType?
- @interface A :
- NSObject — (instancetype)init;
- @interface B : A
The init method from A is inherited to B. However, in both classes the method has a different return type. In A the return type is A and in B the return type is B.
There is no other way to declare the return type for initializers correctly. Note that most programming languages with classes don’t even have return types for constructors, therefore they completely avoid the issue.
This is the reason why Obj-C needs instancetype but of course it can be used outside initializers, too.
20) Are id and instanceType same? If not, what are differences between them?
In your code, replace occurrences of id as a return value with instancetype where appropriate. This is typically the case for init methods and class factory methods. Even though the compiler automatically converts methods that begin with “alloc,” “init,” or “new” and have a return type of id to return instancetype, it doesn’t convert other methods. Objective-C convention is to write instancetype explicitly for all methods.
21) Does Objective-C have function overloading?
objective-C does not support method overloading, so you have to use different method names.
22) What is delegate? Can delegates be retained?
A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program.
It’s up to you. If you declare it to be retained (strong in ARC) it’ll be retained.
The rule is to not retain it because it’s already retained elsewhere and more important you’ll avoid retain cycles.
23) What is class extension? Why do we require them?
Objective-C allows you to add your own methods to existing classes through categories and class extensions.
Class Extensions Extend the Internal Implementation.
A class extension bears some similarity to a category, but it can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension). The methods declared by a class extension are implemented in the @implementation block for the original class so you can’t, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString.
The syntax to declare a class extension is similar to the syntax for a category, and looks like this:
- @interface ClassName ()
Because no name is given in the parentheses, class extensions are often referred to as anonymous categories. Unlike regular categories, a class extension can add its own properties and instance variables to a class.
24) Who calls dealloc method? Can we implement dealloc in ARC? If yes, what is the need to do that?
dealloc is called as a result of memory management. Once an objects “retainCount” reaches 0 then a dealloc message is automatically sent to that object.
You should never call dealloc on objects unless it is a call to [super dealloc]; at the end of an overridden dealloc.
- [ivar release]; //Release any retained variables before super dealloc
- [super dealloc]; //Only place in your code you should ever call dealloc
25) Can you write setter method for a retain property?
Yes, To provide custom access logic, you will need to write your own getter and setter methods.
26) How does dispatch_once manages to run only once?
dispatch_once() is synchronous process and all GCD methods do things asynchronously (case in point, dispatch_sync() is synchronous)
The entire idea of dispatch_once() is “perform something once and only once”, which is precisely what we’re doing. dispatch_once that’s used to guarantee that something happens exactly once, no matter how violent the program’s threading becomes.
27) What are NSAutoreleasePool? When to use them?
The NSAutoreleasePool class is used to support Cocoa’s reference-counted memory management system. An autorelease pool stores objects that are sent a release message when the pool itself is drained.
Also, If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks. For example, in place of:
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- // Code benefitting from a local autorelease pool.
- [pool release];
- You would write:
- // Code benefitting from a local autorelease pool.
@autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC.
28) Does a thread created using performSelectorInBackground:withObject: creates its own autorelease pool?
The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
- [myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads, see “Configuring Thread Attributes.”
29) Is Objective C, a dynamic language? True/False, explain.
True, Objective-C (don’t forget the hyphen) is a cross between C and Smalltalk. The former is a statically typed language. The latter is dynamically typed. So Objective-C is not only a dynamic language.
30) What happens when we invoke a method on a nil pointer?
A message sent to a nil object is perfectly acceptable in Objective-C, it’s treated as a no-op. There is no way to flag it as an error because it’s not an error, in fact it can be a very useful feature of the language. It returns 0, nil, a structure filled with 0s, etc.
Learn Best Objective C Training to Get Most In-Demand IT Skills
- Instructor-led Sessions
- Real-life Case Studies
31) When might you use a CFArray/Dictionary instead of a NSArray/Dictionary?
Core Foundation is the brains of the operation. It’s written mostly in C. It was created with Apple’s acquisition of NEXT and their APIs and owes a lot to them. The NS* classes are often just Objective C abstract interfaces built on top of the CF* types. So, when you ask why both CFArray and NSArray exist, the answer is that they actually don’t. NSArrays are CFArrays, NSStrings are CFStrings, etc. That’s why toll-free-bridging is possible.
32) What is toll-free bridging and when is it useful?
Toll-free bridging means that the data structures are interchangeable. It is just as simple as casting — that’s the “toll-free” part. Anyplace you can use the type on one side of the bridge, you can use the other. So, for example, you can create a CFString and then send NSString messages to it, or you can create an NSArray and pass the array to CFArray functions.
33) What does @synchronized() do?
The @synchronized directive is a convenient way to create mutex locks on the fly in Objective-C code. The @synchronized directive does what any other mutex lock would do — it prevents different threads from acquiring the same lock at the same time.
34) What is the difference between underscore and self (i.e self.xx and _xx) ?
when you are using the self.XX, you access the property via the setter or getter.
when you are using the _XX, you access the property directly skip the setter or getter
35) What is an extension?
Extensions are actually categories without the category name. It’s often referred as anonymous categories. The syntax to declare a extension uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it just adds parentheses, as shown below
- @interface ClassName ()
36) What is a process, thread?
Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
37) Reflection? Class Introspection? is there anything in objc and cocoa?
Class Introspection: It is the ability to provide information about objects/classes at runtime . Objective C runtime supports introspection. A small sample of the type of information provided by the objC runtime
- names of methods of class from a class object.
- information about method arguments
- implementation(IMP) of individual methods of a class
- Information about instance variables of a class
Reflection: Its the ability to add new classes and to add/modify interfaces of existing classes. It also includes the ability to modify the relationship between classes For example, the objC runtime allows new classes to be added, methods to be added to a class and instance variables to be added to a class created at runtime. It also allows the superclass of a class to be replaced by another class.
Swizzling: The term “Swizzling” in objective C refers to exchanging the implementation of two methods(class or instance) at runtime. So you apply introspection to access method implementations and reflection to actually exchange the method implementation to achieve swizzling.
38) How to make a code snippet thread safe?
Thread-safe code is code that remains correct when executed by multiple threads. Thus, No sequence of operations can violate the specification.
1 Invariants and conditions will hold during multithread execution without requiring additional synchronization by the client
2. The high level takeaway point is: thread-safe requires that the specification holds true during multithread execution. To actually code this, we have to do just one thing: regulate the access to mutable shared state
3. And there are three ways to do it: Prevent the access. Make the state immutable. Synchronize the access.
The first two are simple. The third one requires preventing the following thread-safety problems:
liveness deadlock: two threads block permanently waiting for each other to release a needed resource.
livelock: a thread is busy working but it’s unable to make any progress.
starvation: a thread is perpetually denied access to resources it needs in order to make progress.
safe publication: both the reference and the state of the published object must be made visible to other threads at the same time.
race conditions: A race condition is a defect where the output is dependent on the timing of uncontrollable events. In other words, a race condition happens when getting the right answer relies on lucky timing. Any compound operation can suffer a race condition, example: “check-then-act”, “put-if-absent”. An example problem would be if (counter) counter — ;, and one of several solutions would be
- if (counter) counter — ;
39) What happens when you create a block?
Blocks are also used for callbacks, defining the code to be executed when a task completes. As an example, your app might need to respond to a user action by creating an object that performs a complicated task, such as requesting information from a web service. Because the task might take a long time, you should display some kind of progress indicator while the task is occurring, then hide that indicator once the task is complete.
40) What is the “is a” member?
Objective-C objects are basically C structs. Each one contains a field called is a, which is a pointer to the class that the object is an instance of (that’s how the object and Objective-C runtime knows what kind of object it is).
41) What happens if you add your just created object to a mutable array, and you release your object?
It depends. If you owned the object before adding it to the array, you still must release your own ownership claim to avoid a leak — the array’s ownership claim on the object is separate, and does nothing to absolve you of your own responsibility with respect to the memory management rules.
- Object *obj = [[Object alloc] init];
- [anArray addObject:obj];
- [obj release];
On the other hand, if you did not own the object, then you still don’t own it after you add it to the array, and still must not release it. The array does establish its own ownership claim, but just like your own code, it’s responsible for balancing its own claims.
- Object *obj = [Object object];
- [anArray addObject:obj];
- // or, avoiding a temp variable
- [anArray addObject:[Object object]];
42) What happens with the objects if the array is released?
Releasing the array has the same effect as removing all the items from the array. That is, the array no longer claims ownership of them. If anyone else has retained the objects, they’ll continue to exist. If not, they’ll be deallocated.
43) What can’t we put into an array or dictionary?
nil is not an object that you can add to an array: An array cannot contain nil. This is why addObject:nil crashes.
44) How can we put nil it into dictionary/array?
The nil in initWithObjects: is only there to tell the method where the list ends, because of how C var args work. When you add objects one-by-one with addObject: you don’t need to add a nil.
45) What is posing in Objective C?
Posing. Objective-C permits a class to entirely replace another class within an application. The replacing class is said to “pose as” the target class. All messages sent to the target class are then instead received by the posing class.
46) Can we create Dynamic Classes in Objective C? If Yes, Explain how to create with a valid use case?
For instantiating a class using its name, you can use
- NSClassFromString: id obj = [[NSClassFromString(@”MySpecialClass”) alloc] init];
47) What happen if we send any message to an object which is released?
Calling release on an object does not necessarily mean it’s going to be freed. It just decrements the object’s retain count. It’s not until the retain count reaches 0 the object gets freed (and even then, the object might be in an autorelease pool and still not be freed quite then).
So, you might release your object but you could still be pointing to it. And then it could get autoreleased. And then you send it a message — but maybe the object is garbage now.
48) What are the CPU architectures supported by iOS devices?
Armv7s supported from iPhone 5, 5c, 5S, iPod touch-5, iPad-4, iPad Air. that’s nothing but based on processor. Armv7s designed for A6 processor. Supporting from IOS6+. It’s also support for 64-bit coding but processing get slow in those devices with armv7s instruction set.
Same as, Arm64 devices are from Iphone 5s, iPad Air. That’s related to A7 Processor. Best advantage of these device is 64-bit support.
49) Can I write some C++ function in same .m file? Will it compile? If no, what changes should I do to compile it?
The easiest solution is to simply tell Xcode to compile everything as Objective C++.
Set your project or target settings for Compile Sources As to Objective C++ and recompile.
Then you can use C++ or Objective C everywhere.
50) What are the types of iOS binaries you can create using XCode? (.app, .ipa, .a, .framework)
you can create .app,.ipa,.a and .framework
Get Best Objective C Certification Course from Certified ExpertsWeekday / Weekend BatchesSee Batch Details
51) Can a static library (.a) contain resources like images, sound files etc?
NO, You can’t provide anything other than code with a static library. This is because .a files are a simple archive of object files, with the added ability under Mac/iOS of supporting multiple CPU architectures.
The only option you have is to create a Framework, which can provide code as well as other resources.
52) What is bundle?
A bundle is simply a self contained executable file. When you run it, it executes a main function that is defined inside, and uses only the resources that it contains.
53) Explain application life cycle or application states.
These states are known as states of the app’s lifecycle. As an app moves through the states of its lifecycle, the state of the app is defined by its level of activity such as Not Running, Active or Suspended.
Here’s more information about the states:
- When an app is in the Not Running state, either the app hasn’t been launched or the system shut it down.
- When an app starts, it transitions through a short state, called the Inactive state. It’s actually running, but it’s performing other functions and isn’t ready to accept user input or events.
- An app in an Active state is running in the foreground and receiving events. This is the normal mode for foreground apps — apps that don’t have to run in the background without a user interface.
- When an app is in the Background state, its user interface isn’t visible, but it is running. Most apps transition through this state on their way to being suspended.
- An app may need (and request) extra execution time and may stay in this state for a time. In addition, certain apps run in the background. Such an app enters the Background state directly and doesn’t go through the Inactive state.
- The iOS system may move an app to a Suspended state. Here the app is in the background but is not running code. It does stay in memory, though. If a low-memory condition occurs, the system may purge apps in the suspended state without notice. Note that, according to Apple’s standards, only the iOS system can kill an app.
54) Why create a custom view?
You can also create a custom view to to encapsulate the visual appearance and behavior of your own reusable component. For example, in a news reading application we might want a standard component to display images with a caption using a consistent style on both the home page view controller as well as the individual story view controller.
55) What are the size classes?
Size classes are traits assigned to user interface elements, like scenes or views. They provide a rough indication of the element’s size.
56) How we can layout subviews in a view?
addSubview causes layoutSubviews to be called on the view being added, the view it’s being added to (target view), and all the subviews of the target.
57) Difference between UIWindow and UIView.
Windows do not have any visible content themselves but provide a basic container for your application’s views. Views define a portion of a window that you want to fill with some content. Typically, there is only one window in an iOS application.
58) Can we have multiple UIWindows in iOS?
Yes, apps may have an additional window for content displayed on an external display.
59) What are benefits of collections views?
- Allows customizable layout that can be very complex(example: different sizing of each cell)
- Supports multiple cells in one row
- Provides horizontal scroll direction, eliminates the need to create scroll view to achieve the same effect
- Supports custom animations for cells based on layout
- Can implement drag and drop functionality
- More options for headers and footers settings, it does not need to be anchored on the top or bottom
- Does not include blank cells
60) Difference in Xib/storyboard vs nib?
There are things you can do with a storyboard that you can’t do with a nib. A storyboard lets you create segues between view controllers, and it lets you design table view cells in-place.
There are things you can do with a nib that you can’t do with a storyboard. In a nib, you can create references to the File’s Owner placeholder. You can create multiple top-level views, edit them, and create connections between them. See this answer for an example of why you’d want to do that. You can add external object placeholders (a rarely-used feature).
61) How do you declare a variable in Objective-C?
Variables in Objective-C are declared using the syntax: data_type variable_name;
62) What is the difference between a class and an object in Objective-C?
In programming, a class serves as a blueprint or pattern that outlines the characteristics and actions of objects. Conversely, objects are concrete entities generated based on those class specifications.
63) Explain the @interface and @implementation directives.
@interface is used to declare the public interface of a class, while @implementation contains the implementation of the methods declared in the interface.
64) What is the purpose of the “retain,” “strong,” “copy,” and “weak” keywords in Objective-C?
These keywords are used to specify the memory management behavior for object properties. “retain” and “strong” indicate strong ownership, “copy” creates a copy of the object, and “weak” creates a non-retaining reference.
65) Explain the difference between “instancetype” and “id” in Objective-C.
“instancetype” is used to declare the return type of factory methods, ensuring the correct return type based on the class hierarchy. “id” is a generic object pointer that can represent any Objective-C object.
66) What is the use of #import and #include directives?
#import is used to include header files and ensures that they are only included once, preventing duplicate declarations. #include includes the content of the specified file directly.
67) What is KVC (Key-Value Coding) in Objective-C?
KVC allows you to access object properties using key strings at runtime, providing a mechanism to access and modify object properties dynamically.
68) How do you create a singleton in Objective-C?
A singleton is created by implementing a class method that returns a shared instance of the class, ensuring only one instance exists throughout the application’s lifecycle.
69) Difference between dot and square bracket notation for object access?
Dot notation is used for property access, while square bracket notation is used for method invocation and can also be used for property access. Dot notation is more concise but cannot be used with methods that take arguments.
70) How do you achieve inheritance in Objective-C?
In Objective-C, inheritance is achieved using the “:” symbol. For example:
@interface SubClass : SuperClass
// Properties and methods for SubClass
71) Explain the concept of access specifiers.
Objective-C does not have explicit access specifiers like public, private, or protected. By convention, instance variables are typically declared in the class interface, and methods are declared in the class interface or implementation.
72) What distinguishes an instance method from a class method?
A class method is associated with the class itself and is called on the class, while an instance method is associated with individual objects and is called on instances of the class.
73) What is composition in Objective-C?
Composition is a design principle where a class contains one or more objects of other classes as instance variables, allowing it to use their functionalities.
74) How do you implement composition?
Composition is achieved by declaring an instance variable of another class within the interface of the containing class and using it to access the functionalities of the contained class.
75) What are categories in Objective-C?
Without changing the way the class was implemented initially, categories let you add new methods to existing classes. They are useful for adding functionality to system classes or third-party libraries.
76) What is the difference between strong and weak references in Objective-C?
Strong references keep an object in memory until the reference is explicitly set to nil, while weak references do not prevent the object from being deallocated.
77) What is the purpose of protocols in Objective-C?
Protocols define a set of methods that a class can implement to conform to a specific behavior or functionality.
78) How do you work with arrays and dictionaries in Objective-C?
Arrays are created using NSArray or NSMutableArray, while dictionaries are created using NSDictionary or NSMutableDictionary.
79) What contrasts a shallow copy from a deep copy of an array?
A shallow copy creates a new array with references to the same objects, while a deep copy creates a new array with copies of the objects.
80) How do you handle multi-threading in Objective-C?
TMulti-threading can be managed using NSThread, GCD (Grand Central Dispatch), or NSOperationQueue.
81) Explain the NSNotification mechanism in Objective-C.
NSNotification allows objects to broadcast information to other objects without knowing about them directly, enabling loose coupling between components.
82) What are the benefits of using dispatch_async for multithreading in Objective-C?
dispatch_async allows you to perform tasks asynchronously, which improves responsiveness and performance in multi-core environments.
83) How do you handle exceptions in Objective-C?
Objective-C uses the @try, @catch, and @finally blocks for exception handling similar to other programming languages.
84) Who introduced Objective-C & when?
Objective-C was created by Tom Love and Brad Cox at their company Stepstone in the early 1980s.
85) How do I get an IMP given a SEL ?
This can be done by sending a methodFor: message :
IMP myImp = [myObject methodFor:mySel];
86) How do you manage memory in Objective C?
Memory allocation in Objective C is done dynamically. This means memory is allocated during the runtime of any program. It is being utilized and later it is freed when it is no longer required. This helps in using as little memory as possible. In this entire lifecycle of memory, the objects take up as much memory as they need and then free them when it is not required. For allocating memory in Objective C there are two ways:
- Manual Retain Release (MRR): In this type of memory management, memory is explicitly managed and all objects have kept a track of. It uses the reference counting model for keeping this track.
- Automatic Reference Counting (ARC): Here the system is capable of inserting an appropriate memory management method calls which are called the runtime.
The two main drawbacks with memory management are that once they are over freeing it causes to multiple system crashes and when it is not freeing then it leads to memory leaks, which results in the increase in memory footprint of the application.
87) What is declared properties in Objective C?
In Objective C, any property which is to be used it can be defined by declaring different instance variables by implementing getter and setter methods which help to enforce encapsulation. There are three aspects to properties. These include the declaration, implementation, and access. The properties can be declared in any class, category, and protocols in the declarative section. The syntax for this is as follows:
- @property(attributes…)type propertyName
It also has attributes which are optional. Attributes can be as follows:
- Readonly: This property can only be read and not written into. This compiler does not have a setter accessor.
- Read-write: This property enables reading and writing both. The default mode is read-only.
- Assign: This is the simple assignment which can be used in the implementation of any setter.
- Retain: Retain is sent to the property once it is assigned.
- Copy: Like retain this operation is also performed once the property is assigned
88) What are the characteristics of a category?
A category has the following characteristics: A category should be declared for any class even though there is no original source code available for implementation. The methods that are defined in a particular category are available for all instances to the class where it actually belongs. It can also be used in the subclasses of the original class like inheritance. There should not be any variation in a method which is appended by any category. Once it is implemented by the original class it can be used at runtime.
89) What is Retain count?
This is the basic Objective C Interview Question asked in an interview. The policy of ownership is implemented through reference counting. This retain count is taken after the retain method. Each object has a retain count and when an object is created its default retain count is 1. When this newly created object is sent as a retain message then the count is increased by 1. This count is decreased by 1 when an object is sent as the release message. It is also decreased when an object is sent an autorelease message at the end of the current autorelease pool. The object is released and deallocated when a retain count is decreased to 0.
90) When do we use NSArray and NSMutableArray?
NSArray is advised to be used when data in the array is not going to change. An example of this can be a company name which is going to seldom change and hence NS Array can be used so that no one manipulates it.
NSMutable Array: Unlike NS Array this array is used when data in an array tends to change. Here an example can be considered of a function which has values passing to the array as function and this function will append some elements to that array. At this time NSMutable array can be used.
91) Is it possible to use ARC and Non-ARC code together in a project?
Yes, a project can use both ARC and Non-ARC codes. When a project chooses Non-ARC codes then –fobj-arc compiler flag is set. This ARC can be disabled for specific classes by using –fno-objc-arc.
This entire process can be done by Xcode → Project→ Build Phase→ Compile Sources→ Double Click on class and set the –fno-objc-arc.
92) What are the methods of using NSURL connection?
The methods that can be used in NSURL connection are the following connections:
- A connection which received the response
- A connection which receives data
- A connection which fails with error
- A Connection which did finish on loading
93) How does message work in Objective C?
This is the most asked Objective C Interview Questions in an interview. Messaging is not bound to happen until a method is implemented in Objective C. A call messaging function objc_msgSend() is called when compiler transforms a message expression. This function connects to the receiver and the name of the method is mentioned in the message.
94) What is atomic and non-atomic in Objective C and which one is considered to be a default?
This method is used to specify the accessor methods which are not atomic. This ensures that the process which is being currently run is completed by the CPU before any other process accesses the variable. Non-atomic is for the variables which are non-atomic. These are faster but not thread safe.
95) In which tech conference was the latest version launched?
It was launched at the Worldwide Developers Conference.
96) State the two types of protocols it encompasses.
The two different types of protocols Objective C encompasses are … formal and informal.
97) What are the categories used for?
In order to add methods to an already existing class, a category is needed. Categories are also used to disseminate implementing their respective classes into individual source files.
98) State the full form of GCD.
The full form of GCD is Grand Central Dispatch.
99) What is the function of GCD?
The main advantage of creating a GCD is that only one thread is developed to execute the blocks and the execution of the same happens sequentially. Hence there is nothing unexpected to preempt.
100) State the full forms of KVC and KVO?
The full form of KVC is Key-Value Coding and the full form of KVO is Key-Value Observing.