原帖地址 http://huntmyideas.weebly.com/blog/ios-interview-questions-and-answers-part12
1.What is init ?
Answer:- - init is an instance method, used to initialize a particular object 2.What is new ? Answer:- NSObject implements a class method "new" which simply calls " alloc" and " init" 3.What is the difference between init and new ? Answer:- new doesn't support custom initializers (like initWithString) alloc-init is more explicit than new
4.What is retain ?
Answer:- it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain" 5.What is ARC? Answer:- Automatic Reference Counting, or ARC was introduced in iOS 5,is a feature of the new LLVM 3.0 compiler and it completely does away with the manual memory management.you no longer call retain, release and autorelease.With Automatic Reference Counting enabled, the compiler will automatically insert retain, release and autorelease in the correct places in your program ARC is not a runtime feature (except for one small part, the weak pointer system), nor is it *garbage collection* that you may know from other languages.All that ARC does is insert retains and releases into your code when it compiles it. OR ARC is a compiler-level feature that simplifies the process of managing the lifetimes of Objective-C objects. Instead of you having to remember when to retain or release an object, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls at compile time. 6.What is atomic? Answer:- -Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behaviour -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword. Example : @property (retain) NSString *name; @synthesize name; 7.What is nonatomic? Answer:- -Nonatomic means multiple thread access the variable(dynamic type). -Nonatomic is thread unsafe. -but it is fast in performance -Nonatomic is NOT default behavior,we need to add nonatomic keyword in property attribute. -it may result in unexpected behavior, when two different process (threads) access the same variable at the same time. Example: @property (nonatomic, retain) NSString *name; @synthesize name; 8.What is strong (iOS4 = retain ) ? Answer:- -it says "keep this in the heap until I don't point to it anymore" -in other words " I'am the owner, you cannot dealloc this before aim fine with that same as retain" -You use strong only if you need to retain the object. -By default all instance variables and local variables are strong pointers. -We generally use strong for UIViewControllers (UI item's parents) -strong is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong means that you own the object. Example: @property (strong, nonatomic) ViewController *viewController; @synthesize viewController; 9.What is weak (iOS4 = unsafe_unretained )? Answer:- -it says "keep this as long as someone else points to it strongly" -the same thing as assign, no retain or release -A "weak" reference is a reference that you do not retain. -We generally use weak for IBOutlets (UIViewController's Childs).This works because the child object only needs to exist as long as the parent object does. -a weak reference is a reference that does not protect the referenced object from collection by a garbage collector. -Weak is essentially assign, a unretained property. Except the when the object is deallocated the weak pointer is automatically set to nil Example : @property (weak, nonatomic) IBOutlet UIButton *myButton; @synthesize myButton; Explain: Imagine our object is a dog, and that the dog wants to run away (be deallocated). Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached. Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it. As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out. When we use weak? The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released). 10.What is retain = strong ? Answer :- -it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain" Example: @property (nonatomic, retain) NSString *name; @synthesize name; 11.What is assign? Answer:- -assign is the default and simply performs a variable assignment -assign is a property attribute that tells the compiler how to synthesize the property's setter implementation -I would use assign for C primitive properties and weak for weak references to Objective-C objects. Example: @property (nonatomic, assign) NSString *address; @synthesize address; 12.What is unsafe_unretained? Answer:- -unsafe_unretained is an ownership qualifier that tells ARC how to insert retain/release calls -unsafe_unretained is the ARC version of assign. Example: @property (nonatomic, unsafe_unretained) NSString *nickName; @synthesize nickName; 13.What is copy? Answer:- -copy is required when the object is mutable. -copy specifies the new value should be sent -copy on assignment and the old value sent -release. -copy is like retain returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments. -if you use copy then you still need to release that in dealloc. -Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy. Example: @property (nonatomic, copy) NSArray *myArray; @synthesize myArray; 14.What is readonly? Answer:- -declaring your property as readonly you tell compiler to not generate setter method automatically. -Indicates that the property is read-only. -If you specify readonly, only a getter method is required in the @implementation block. If you use the @synthesize directive in the @implementation block, only the getter method is synthesized. Moreover, if you attempt to assign a value using the dot syntax, you get a compiler error. Example: @property (nonatomic, readonly) NSString *name; @synthesize name; 15.What is readwrite? Answer:- -setter and getter generated. -Indicates that the property should be treated as read/write. -This attribute is the default. -Both a getter and setter method are required in the @implementation block. If you use the @synthesize directive in the implementation block, the getter and setter methods are synthesized. Example: @property (nonatomic, readwrite) NSString *name; @synthesize name; 16.What is self in Objective c? Answer :- self is a special variable in Objective-C, inside an instance method this variable refers to the receiver(object) of the message that invoked the method, while in a class method self will indicate which class is calling. Self refers to the actual object that is executing the current method, it is an invisible argument passed automatically by the runtime environment to your instance methods. Using self uses the getter and setter methods, while leaving it out modifies the instance variable directly. In order to use self.age, you must have age declared as a property with the @propertysyntax. I typically try to use self wherever I can. 17.What is super in objective C? Answer:- It's a keyword that's equivalent to self, but starts its message dispatch searching with the superclass's method table. Super is not a pointer to a class. Super is self, but when used in a message expression, it means "look for an implementation starting with the superclass's method table." 18.Difference between shallow copy and deep copy? Answer:- Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements. Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated. OR Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data. Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy. Char *A = {‘a’,’b’,’c’}; Char *B = {‘x’,’y’,’z’}; B = A; Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array. while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected. 19.What is purpose of delegates? Answer:- A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three comment delegates: -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error -(void)connectionDidFinishLoading:(NSURLConnection *)connection -(void)connection:(NSURLConnection *)connection didReceiveResponse -- (NSURLResponse *)response 20.what is retain count in objective c? Answer:- The retainCount is the number of ownership claims there are outstanding on the object.You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. All of these increment the retainCount. 21.How would you create your own custom view? Answer:- By Subclassing the UIView class. When you build your iOS app, Xcode packages it as a bundle. App bundle is a directory in the file system that groups related resources together in one place. An iOS app bundle contains the app executable file and supporting resource files such as app icons, image files, and localized content. 23. Whats the difference between frame and bounds? Answer:- The frame of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within. The bounds of a view is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0). 24.Is a delegate retained? Answer:- No, the delegate is never retained! Ever! 25.What are the App states. Explain them? Answer:- 1.Not running State: The app has not been launched or was running but was terminated by the system. 2.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. 3.Active state: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps. 4.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.” 5.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. 26.Whats the difference between NSArray and NSMutableArray? Answer:- NSArrayʼs contents can not be modified once itʼs been created whereas a NSMutableArray can be modified as needed, i.e items can be added/removed from it. 27.Explain retain counts. Answer:- Retain counts are the way in which memory is managed in Objective-C. When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. If an objectʼs retain count is reduced to 0, it is deallocated. 28.Why do we need to use @Synthesize? Answer:- We can use generated code like nonatomic, atomic, retain without writing any lines of code. We also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.@property is really good for memory management, for example: retain. How can you do retain without @property? if (_variable != object) { [_variable release]; _variable = nil; _variable = [object retain]; } How can you use it with @property?self.variable = object; When we are calling the above line, we actually call the setter like [self setVariable:object] and then the generated setter will do its job. 29.Multitasking support is available from which version? Answer:- iOS 4.0. 30.What is difference between NSNotification and delegate? Answer:- Delegate is passing message from one object to other object. It is like one to one communication while NSNotification is like passing message to multiple objects at the same time. All other objects that have subscribed to that notification or acting observers to that notification can or can’t respond to that event. Notifications are easier but you can get into trouble by using those like bad architecture. Delegates are more frequently used and are used with help of protocols. 31.Explain Nil - NULL – NSNULL A nswer:- There are 3 ways to represent a null value in Objective-C. Nil -> Absence of value with Objective-C object variables. Null -> Absence of value with C- style pointers. N SNULL ->A nil boxed as an object for storage in a collection. 32.Whats a struct? Answer:- A struct is a special C data type that encapsulates other pieces of data into a single cohesive unit. Like an object, but built into C. 33.How many bytes we can send to apple push notification server? Answer:- 256bytes. 34.What is push notification? Answer:- Imagine, you are looking for a job. You go to software company daily and ask sir “is there any job for me” and they keep on saying no. Your time and money is wasted on each trip.(Pull Request mechanism) So, one day owner says, if there is any suitable job for you, I will let you know. In this mechanism, your time and money is not wasted. (Push Mechanism) How it works? This service is provided by Apple in which rather than pinging server after specific interval for data which is also called pull mechanism, server will send notification to your device that there is new piece of information for you. Request is initiated by server not the device or client. Flow of push notification Your web server sends message (device token + payload) to Apple push notification service (APNS) , then APNS routes this message to device whose device token specified in notification. 35.What is keyword Atomic in objective C? Answer:- When you place keyword atomic with a property, it means at one time only one thread can access it. 36.Can we use two tableview controllers on one view controller? Answer:- Yes, we can use two tableviews on the same view controllers and you can differentiate between two by assigning them tags or you can also check them by comparing their memory addresses. 37.Is the delegate for a CAAnimation retained? Answer:- Yes it is!! This is one of the rare exceptions to memory management rules. 38.Explain the difference between NSOperationQueue concurrent and non-concurrent? Answer:- In the context of an NSOperation object, which runs in an NSOperationQueue, the terms concurrent and non-concurrent do not necessarily refer to the side-by-side execution of threads. Instead, a non-concurrent operation is one that executes using the environment that is provided for it while a concurrent operation is responsible for setting up its own execution environment. 39.What is advantage of categories? What is difference between implementing a category and inheritance? Answer:- You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without subclassing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality. 40.Difference between categories and extensions? Answer:- Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally) — it’s meant to be just that, an extension. 41.What are mutable and immutable types in Objective C? Answer:- Mutable means you can change its contents later but when you mark any object immutable, it means once they are initialized, their values cannot be changed. For example, NSArray, NSString values cannot be changed after initialized. 42.When we call objective c is runtime language what does it mean? Answer:- Objective-C runtime is runtime library that is open source that you can download and understand how it works. This library is written in C and adds object-oriented capabilities to C and makes it objective-c. It is only because of objective c runtime that it is legal to send messages to objects to which they don’t know how to respond to. Methods are not bound to implementation until runtime. Objective-C defers its decisions from compile time to run time as much as it can. For example, at runtime, it can decide to which object it will send message or function. 43.What are KVO and KVC?KVC? Answer:- Normally instance variables are accessed through properties or accessors but KVC gives another way to access variables in form of strings. In this way your class acts like a dictionary and your property name for example “age” becomes key and value that property holds becomes value for that key. For example, you have employee class with name property. You access property like NSString age = emp.age; setting property value. emp.age = @”20″; Now how KVC works is like this [emp valueForKey:@"age"]; [emp setValue:@"25" forKey:@"age"]; KVO : The mechanism through which objects are notified when there is change in any of property is called KVO. For example, person object is interested in getting notification when accountBalance property is changed in BankAccount object.To achieve this, Person Object must register as an observer of the BankAccount’s accountBalance property by sending an addObserver:forKeyPath:options:context: message. 45.What is polymorphism? Answer:- This is very famous question and every interviewer asks this. Few people say polymorphism means multiple forms and they start giving example of draw function which is right to some extent but interviewer is looking for more detailed answer. Ability of base class pointer to call function from derived class at runtime is called polymorphism. For example, there is super class human and there are two subclasses software engineer and hardware engineer. Now super class human can hold reference to any of subclass because software engineer is kind of human. Suppose there is speak function in super class and every subclass has also speak function. So at runtime, super class reference is pointing to whatever subclass, speak function will be called of that class. I hope I am able to make you understand. 46.What is responder chain? Answer: - Suppose you have a hierarchy of views such like there is superview A which have subview B and B has a subview C. Now you touch on inner most view C. The system will send touch event to subview C for handling this event. If C View does not want to handle this event, this event will be passed to its superview B (next responder). If B also does not want to handle this touch event it will pass on to superview A. All the view which can respond to touch events are called responder chain. A view can also pass its events to UIViewController. If view controller also does not want to respond to touch event, it is passed to application object which discards this event. 47.Swap the two variable values without taking third variable? Answer:- int x=10; int y=5; x=x+y; NSLog(@”x==> %d”,x); y=x-y; NSLog(@”Y Value==> %d”,y); x=x-y; NSLog(@”x Value==> %d”,x); 48. When we call objective c is runtime language what does it mean? Answer:- Objective-C runtime is runtime library that is open source that you can download and understand how it works. This library is written in C and adds object-oriented capabilities to C and makes it objective-c. It is only because of objective c runtime that it is legal to send messages to objects to which they don’t know how to respond to. Methods are not bound to implementation until runtime. Objective-C defers its decisions from compile time to run time as much as it can. For example, at runtime, it can decide to which object it will send message or function. 49.Can we use one tableview with two different datasources? How you will achieve this? Answer:- Yes. We can conditionally bind tableviews with two different data sources. 50.Difference between Atomic and non-atomic ? Answer:- Atomic:- Is default behavior will ensure the present process is completed by the cpu, before another process access the variable not fast, as it ensures the process is completed entirely Non-Atomic -Is NOT default behavior -faster (for synthesized code, ie for variable created using @property, @synthesize ) -not thread safe -may result in unexpected behavior, when two different process access the same variable at the same time |