iOS Interview Questions

“release” frees a memory. “drain” releases the NSAutoreleasePool itself.

266.NSAutoReleasePool : release vs drain
Strictly speaking, from the big picture perspective drain is not equivalent to release:
In a reference-counted environment, drain does perform the same operations as release, so the two are in that sense equivalent. To emphasise, this means you do not leak a pool if you use drain rather than release.
In a garbage-collected environment, release is a no-op. Thus it has no effect. drain, on the other hand, contains a hint to the collector that it should “collect if needed”. Thus in a garbage-collected environment, using drain helps the system balance collection sweeps.

267.autorelease vs release
Autorelase: By sending an object an autorelease message, it is added to the local AutoReleasePool, and you no longer have to worry about it, because when the AutoReleasePool is destroyed (as happens in the course of event processing by the system) the object will receive a release message, its RetainCount will be decremented, and the GarbageCollection system will destroy the object if the RetainCount is zero.
Release: retain count is decremented at this point.

268.Autorelease Pool
Autorelease pools provide a mechanism whereby you can send an object a “deferred” release message. This is useful in situations where you want to relinquish ownership of an object, but want to avoid the possibility of it being deallocated immediately (such as when you return an object from a method). Typically, you don’t need to create your own autorelease pools, but there are some situations in which either you must or it is beneficial to do so.

269.How autorelease pool is managed.
Every time -autorelease is sent to an object, it is added to the inner-most autorelease pool. When the pool is drained, it simply sends -release to all the objects in the pool.
Autorelease pools are simply a convenience that allows you to defer sending -release until “later”. That “later” can happen in several places, but the most common in Cocoa GUI apps is at the end of the current run loop cycle



270.Memory Leak
If RetainingAndReleasing are not properly used then RetainCount for AnObject doesn’t reach 0. It doesn’t crash the application.

271.Event Loop
In a Cocoa application, user activities result in events. These might be mouse clicks or drags, typing on the keyboard, choosing a menu item, and so on. Other events can be generated automatically, for example a timer firing periodically, or something coming in over the network. For each event, Cocoa expects there to be an object or group of objects ready to handle that event appropriately. The event loop is where such events are detected and routed off to the appropriate place. Whenever Cocoa is not doing anything else, it is sitting in the event loop waiting for an event to arrive. (In fact, Cocoa doesn’t poll for events as suggested, but instead its main thread goes to sleep. When an event arrives, the OS wakes up the thread and event processing resumes. This is much more efficient than polling and allows other applications to run more smoothly).
Each event is handled as an individual thing, then the event loop gets the next event, and so on. If an event causes an update to be required, this is checked at the end of the event and if needed, and window refreshes are carried out.

272.Differnce between boxName and self.boxName.
boxName: Accessing directly.
self. boxName: Accessing boxName through accessors. If property/synthesize is not there it will throw error.

273.What it does “@synthesize boxDescription=boxName;” ?
Here you can use boxName or self.boxName. We cant use boxDescription.

274.Collection
In Cocoa and Cocoa Touch, a collection is a Foundation framework class used for storing and managing groups of objects. Its primary role is to store objects in the form of either an array, a dictionary, or a set.

275.Threads and how to use
Use this class when you want to have an Objective-C method run in its own thread of execution. Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi-core computers.
Two ways to create threads…
  • detachNewThreadSelector:toTarget:withObject:
  • Create instances of NSThread and start them at a later time using the “start” method.
NSThread is not as capable as Java’s Thread class, it lacks
  • Built-in communication system.
  • An equivalent of “join()”
276.Threadsafe
When it comes to threaded applications, nothing causes more fear or confusion than the issue of handling signals. Signals are a low-level BSD mechanism that can be used to deliver information to a process or manipulate it in some way. Some programs use signals to detect certain events, such as the death of a child process. The system uses signals to terminate runaway processes and communicate other types of information.
The problem with signals is not what they do, but their behavior when your application has multiple threads. In a single-threaded application, all signal handlers run on the main thread. In a multithreaded application, signals that are not tied to a specific hardware error (such as an illegal instruction) are delivered to whichever thread happens to be running at the time. If multiple threads are running simultaneously, the signal is delivered to whichever one the system happens to pick. In other words, signals can be delivered to any thread of your application.
The first rule for implementing signal handlers in applications is to avoid assumptions about which thread is handling the signal. If a specific thread wants to handle a given signal, you need to work out some way of notifying that thread when the signal arrives. You cannot just assume that installation of a signal handler from that thread will result in the signal being delivered to the same thread.

277.Notification and Observers
A notification is a message sent to one or more observing objects to inform them of an event in a program. The notification mechanism of Cocoa follows a broadcast model. It is a way for an object that initiates or handles a program event to communicate with any number of objects that want to know about that event. These recipients of the notification, known as observers, can adjust their own appearance, behavior, and state in response to the event. The object sending (or posting) the notification doesn’t have to know what those observers are. Notification is thus a powerful mechanism for attaining coordination and cohesion in a program. It reduces the need for strong dependencies between objects in a program (such dependencies would reduce the reusability of those objects). Many classes of the Foundation, AppKit, and other Objective-C frameworks define notifications that your program can register to observe.
The centerpiece of the notification mechanism is a per-process singleton object known as the notification center (NSNotificationCenter). When an object posts a notification, it goes to the notification center, which acts as a kind of clearing house and broadcast center for notifications. Objects that need to know about an event elsewhere in the application register with the notification center to let it know they want to be notified when that event happens. Although the notification center delivers a notification to its observers synchronously, you can post notifications asynchronously using a notification queue (NSNotificationQueue).

278.Delegate vs Notification
The concept of notification differs from delegation in that it allows a message to be sent to more than one object. It is more like a broadcast rather than a straight communication between two objects. It removes dependencies between the sending and receiving object(s) by using a notification center to manage the sending and receiving of notifications. The sender does not need to know if there are any receivers registered with the notification center. There can be one, many or even no receivers of the notification registered with the notification center. Simply, Delegate is 1-to-1 object and Notification can be *-to-* objects.
The other difference between notifications and delegates is that there is no possibility for the receiver of a notification to return a value to the sender.
Typical uses of notifications might be to allow different objects with an application to be informed of an event such as a file download completing or a user changing an application preference. The receiver of the notification might then perform additional actions such as processing the downloaded file or updating the display.

279.Plist
Property lists organize data into named values and lists of values using several object types. These types give you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible. Property lists are frequently used by applications running on both Mac OS X and iOS. The property-list programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically structured combinations of these basic types of objects to and from standard XML. You can save the XML data to disk and later use it to reconstruct the original objects.
The user defaults system, which you programmatically access through the NSUserDefaults class, uses property lists to store objects representing user preferences. This limitation would seem to exclude many kinds of objects, such as NSColor and NSFont objects, from the user default system. But if objects conform to the NSCoding protocol they can be archived to NSData objects, which are property list–compatible objects

280.Helper Objects
Helper Objects are used throughout Cocoa and CocoaTouch, and usually take the form of a delegate or dataSource. They are commonly used to add functionality to an existing class without having to subclass it.

281.Cluster Class
Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness.

282.Differentiate Foundation vs Core Foundation
CoreFoundation is a general-purpose C framework whereas Foundation is a general-purpose Objective-C framework. Both provide collection classes, run loops, etc, and many of the Foundation classes are wrappers around the CF equivalents. CF is mostly open-source , and Foundation is closed-source.
Core Foundation is the C-level API, which provides CFString, CFDictionary and the like.Foundation is Objective-C, which provides NSString, NSDictionary, etc. CoreFoundation is written in C while Foundation is written in Objective-C. Foundation has a lot more classes CoreFoundation is the common base of Foundation and Carbon.

283.Difference between coreData and Database
DatabaseCore Data
Primary function is storing and fetching dataPrimary function is graph management (although reading and writing to disk is an important supporting feature)
Operates on data stored on disk (or minimally and incrementally loaded)Operates on objects stored in memory (although they can be lazily loaded from disk)
Stores “dumb” dataWorks with fully-fledged objects that self-manage a lot of their behavior and can be subclassed and customized for further behaviors
Can be transactional, thread-safe, multi-userNon-transactional, single threaded, single user (unless you create an entire abstraction around Core Data which provides these things)
Can drop tables and edit data without loading into memoryOnly operates in memory
Perpetually saved to disk (and often crash resilient)Requires a save process
Can be slow to create millions of new rowsCan create millions of new objects in-memory very quickly (although saving these objects will be slow)
Offers data constraints like “unique” keysLeaves data constraints to the business logic side of the program

284.Core data vs sqlite.
Core data is an object graph management framework. It manages a potentially very large graph of object instances, allowing an app to work with a graph that would not entirely fit into memory by faulting objects in and out of memory as necessary. Core Data also manages constraints on properties and relationships and maintains reference integrity (e.g. keeping forward and backwards links consistent when objects are added/removed to/from a relationship). Core Data is thus an ideal framework for building the “model” component of an MVC architecture.
To implement its graph management, Core Data happens to use sqlite as a disk store. Itcould have been implemented using a different relational database or even a non-relational database such as CouchDB. As others have pointed out, Core Data can also use XML or a binary format or a user-written atomic format as a backend (though these options require that the entire object graph fit into memory).

285.Retain cycle or Retain loop.
When object A retains object B, and object B retains A. Then Retain cycle happens. To overcome this use “close” method.
Objective-C’s garbage collector (when enabled) can also delete retain-loop groups but this is not relevant on the iPhone, where Objective-C garbage collection is not supported.

286.What is unnamed category.
A named category — @interface Foo(FooCategory) — is generally used to:
  1. Extend an existing class by adding functionality.
  2. Declare a set of methods that might or might not be implemented by a delegate.
Unnamed Categories has fallen out of favor now that @protocol has been extended to support @optional methods.
A class extension — @interface Foo() — is designed to allow you to declare additional private API — SPI or System Programming Interface — that is used to implement the class innards. This typically appears at the top of the .m file. Any methods / properties declared in the class extension must be implemented in the @implementation, just like the methods/properties found in the public @interface.
Class extensions can also be used to redeclare a publicly readonly @property as readwrite prior to @synthesize’ing the accessors.
Example:
Foo.h
@interface Foo:NSObject
@property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end
Foo.m
@interface Foo()
@property(readwrite, copy) NSString *bar;
– (void) superSecretInternalSaucing;
@end
@implementation Foo
@synthesize bar;
…. must implement the two methods or compiler will warn ….
@end 

287.Copy vs mutableCopy.
copy always creates an immutable copy.
mutableCopy always creates a mutable copy.

288.Strong vs Weak
The strong and weak are new ARC types replacing retain and assign respectively.
Delegates and outlets should be weak.
A strong reference is a reference to an object that stops it from being deallocated. In other words it creates a owner relationship.
A weak reference is a reference to an object that does not stop it from being deallocated. In other words, it does not create an owner relationship.

289.__strong, __weak, __unsafe_unretained, __autoreleasing.
Generally speaking, these extra qualifiers don’t need to be used very often. You might first encounter these qualifiers and others when using the migration tool. For new projects however, you generally you won’t need them and will mostly use strong/weak with your declared properties.
__strong – is the default so you don’t need to type it. This means any object created using alloc/init is retained for the lifetime of its current scope. The “current scope” usually means the braces in which the variable is declared
__weak – means the object can be destroyed at anytime. This is only useful if the object is somehow strongly referenced somewhere else. When destroyed, a variable with __weak is set to nil.
__unsafe_unretained – is just like __weak but the pointer is not set to nil when the object is deallocated. Instead the pointer is left dangling.
__autoreleasing, not to be confused with calling autorelease on an object before returning it from a method, this is used for passing objects by reference, for example when passing NSError objects by reference such as [myObject performOperationWithError:&tmp];

290.Types of NSTableView
Cell based and View based. In view based we can put multiple objects.

291.Abstract class in cocoa.
Cocoa doesn’t provide anything called abstract. We can create a class abstract which gets check only at runtime, compile time this is not checked.
@interface AbstractClass : NSObject
@end
@implementation AbstractClass
+ (id)alloc{
if (self == [AbstractClass class]) {
NSLog(@”Abstract Class cant be used”);
}
return [super alloc];
@end

292.Difference between HTTP and HTTPS.
  • HTTP stands for HyperTextTransfer Protocol, whereas, HTTPS is HyperText Transfer Protocol Secure.
  • HTTP transmits everything as plan text, while HTTPS provides encrypted communication, so that only the recipient can decrypt and read the information. Basically, HTTPS is a combination of HTTP andSSL(Secure Sockets Layer). This SSL is that protocol which encrypts the data.
  • HTTP is fast and cheap, where HTTPS is slow and expensive.
As, HTTPS is safe it’s widely used during payment transactions or any sensitive transactions over the internet. On the other hand, HTTP is used most of the sites over the net, even this blogspot sites also use HTTP.
  • HTTP URLs starts with “http:// “ and use port80 by default, while HTTPS URLs stars with “https:// “ and use port 443.
  • HTTP is unsafe from attacks like man-in-the-middleand eavesdropping, but HTTPS is secure from these sorts of attacks.
293.GCD
Grand Central Dispatch is not just a new abstraction around what we’ve already been using, it’s an entire new underlying mechanism that makes multithreading easier and makes it easy to be as concurrent as your code can be without worrying about the variables like how much work your CPU cores are doing, how many CPU cores you have and how much threads you should spawn in response. You just use the Grand Central Dispatch API’s and it handles the work of doing the appropriate amount of work. This is also not just in Cocoa, anything running on Mac OS X 10.6 Snow Leopard can take advantage of Grand Central Dispatch ( libdispatch ) because it’s included in libSystem.dylib and all you need to do is include #import <dispatch/dispatch.h> in your app and you’ll be able to take advantage of Grand Central Dispatch.

294.How you attain the backward compatibility?
Set the Base SDK to Current version of Mac (ex. 10.7)
Set the Deployment SDK to older version (ex.1.4)

295.Call Back.
Synchronous operations are ones that happen in step with your calling code. Most of Cocoa works this way: you send a message to an object, say to format a string, etc, and by the time that line of code is “done”, the operation is complete.
But in the real world, some operations take longer than “instantaneous” (some intensive graphics work, but mainly high or variably latency things like disk I/O or worse, network connectivity). These operations are unpredictable, and if the code were to block until finish, it might block indefinitely or forever, and that’s no good.
So the way we handle this is to set up “callbacks”– you say “go off and do this operation, and when you’re done, call this other function”. Then inside that “callback” function, you start the second operation that depends on the first. In this way, you’re not spinning in circles waiting, you just get called “asynchronously” when each task is done.

296.What is a delegate?
  • What Most People Say:Delegates are used in UITableView to get the data for the table.
  • What You Should Say:Delegates are Apple’s way of implementing call back methods. They allow a class to send information to a different class.
  • Why You Should Say It: “Again, a short answer doesn’t inspire confidence,” Schweitzer explains. “You need to show that you understand the purpose of delegates and how they fit into the architecture of the application without pontificating. The key is to supply just enough information to demonstrate your understanding of a concept or function, then get off the stage.”
297.Describe Waterfall and Agile methodologies.
  • What Most People Say:Waterfall is the older methodology that is not used in modern software development.
  • What You Should Say:Books have been written about this. Briefly, in Waterfall the requirements are defined without much or any interaction with the software development team. In Agile, there is continuous refining of requirements as development proceeds due to constant interaction between those defining the requirements and the people doing the development.
  • Why You Should Say It:Waterfall is older but it’s still used and the interviewer didn’t ask you to rate the two, Schweitzer says. You should explain the differences between the two methodologies, then invite an in-depth conversation by explaining when each is most effective and describing your experience with each one.
298.What are the App states. Explain them?
Not running State: The app has not been launched or was running but was terminated by the system.
Inactive state: The app is running in the foreground but is currently not receiving events. (It may be executing other code though.) An app usually stays in this state only briefly as it transitions to a different state. The only time it stays inactive for any period of time is when the user locks the screen or the system prompts the user to respond to some event, such as an incoming phone call or SMS message.
Active state: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
Background state: The app is in the background and executing code. Most apps enter this state briefly on their way to being suspended. However, an app that requests extra execution time may remain in this state for a period of time. In addition, an app being launched directly into the background enters this state instead of the inactive state. For information about how to execute code while in the background, see “Background Execution and Multitasking.”
Suspended state:The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code. When a low-memory condition occurs, the system may purge suspended apps without notice to make more space for the foreground app.

299.What is the split view controller?
This control is used for ipad application and it contain proper controllers by default
split view controller contain root view controller and detail view controller.
FabGreenTechnologies-Madivala
FabGreenTechnologies.com

No comments:

Post a Comment