iOS interview questions that I've been asked
最近面試問到的一些問題, 記錄一下:
Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.
retain cycle: Two objects hold a strong reference to each other, such that each instance keeps the other alive, the reference counts do not drop to zero, and the instances are not deallocated by ARC. This is known as a strong reference cycle.
A weak reference allows the posibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional - so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).
An unowned reference presumes that it will never become nil during it's lifetime. A unowned reference must be set during initialization - this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred is deallocated, then the app will crash when the unowned reference will be used.
A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not.
#automatic memory management, dealloc
#atomic -> thread safety, nonatomic -> faster
#like closures in swift, callback API
1. What is cocoa and cocoa touch?
Cocoa and Cocoa Touch are the application development environments for OS X and iOS, respectively. Both Cocoa and Cocoa Touch include the Objective-C runtime and two core frameworks:
- Cocoa, which includes the Foundation and AppKit frameworks, is used for developing applications that run on OS X.
- Cocoa Touch, which includes Foundation and UIKit frameworks, is used for developing applications that run on iOS.
2. What's different between NULL and nil and Nil?
The difference is that while NULL represents zero for any pointer, nil is specific to objects (e.g., id) and Nil is specific to class pointers.
Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.
3. What's different between 'weak' and 'strong' property?
weak: will assign the incoming value to it without retaining it. You don't want to have control over the object's lifetime.
strong: (default)assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil will the object get destroyed.
strong: (default)assigns the incoming value to it, it will retain the incoming value and release the existing value of the instance variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil will the object get destroyed.
strong属性指的是对这个对象强烈的占有!不管别人对它做过什么,反正你就是占有着!它对于你随叫随到。weak指的是对这个对象弱弱的保持着联系,每次使用的时候你弱弱的问它一句“还在吗”,如果没人回应(变成nil),就说明它已经离开你了(大概是被系统残忍的回收了吧)。
链接:https://www.zhihu.com/question/20350816/answer/22307399
retain cycle: Two objects hold a strong reference to each other, such that each instance keeps the other alive, the reference counts do not drop to zero, and the instances are not deallocated by ARC. This is known as a strong reference cycle.
3.1. What is the difference between a weak reference and an unowned reference?
Both weak and unowned references do not create a strong hold on the referred object (a.k.a. they don't increase the retain count in order to prevent ARC from deallocating the referred object).A weak reference allows the posibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional - so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).
An unowned reference presumes that it will never become nil during it's lifetime. A unowned reference must be set during initialization - this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred is deallocated, then the app will crash when the unowned reference will be used.
A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not.
4. What is ARC?
Automatic Reference Counting (ARC) is a compiler feature that provides automatic memory management of Objective-C objects. Rather than having to think about retain and release operations, ARC allows you to concentrate on the interesting code, the object graphs, and the relationships between objects in your application.
#automatic memory management, dealloc
5. What is atomic?
With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance.
#atomic -> thread safety, nonatomic -> faster
6. What is BLOCK?
Blocks are a way of defining a single task or unit of behavior without having to write an entire Objective-C class.
You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.
#like closures in swift, callback API
7. What's different between CLASS and STRUCTURE in swift?
The main difference is that structs are value types and classes are reference types. Structures cannot inherit from other types.
Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple reference to the same instance as happens with classes.
Structs there is much less need to worry about memory leaks.
Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple reference to the same instance as happens with classes.
Structs there is much less need to worry about memory leaks.
8. What is a protocol?
It defines a list of required and optional methods that a class must/can implement if it adopts the protocol.
#define , required or optional methods, blueprint
To create custom uiview, just create your own class subclassing UIView, then override initWithFrame or drawRect.
A common example of implicitly unwrapped optionals is how view controller define their IBOutlets.
It would be unwieldy(笨重的) to always unwrap each view outlet inside view controllers.
#question mark, exclamation mark, unwrapping
11.1 Optional Chain
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
12. NSKeyedArchiver
#define , required or optional methods, blueprint
9. What is UIAppliction?
UIApplication is the iOS singleton application base class. It's a major role of app’s application object is to handle the initial routing of incoming user events.10. What is UIView? How to create custom UIView?
UIView is an object that manages the content for a rectangular area on the screen, it responsible for recognizing touches, gestures.To create custom uiview, just create your own class subclassing UIView, then override initWithFrame or drawRect.
11. Optional type
A type that can represent either a wrapped value or nil. It shows the wrapped type's name with a trailing question mark (?
). There are couple ways to unwrapping : if let statement , guard statement, forced unwrapping. But forced unwrapping triggers a runtime error when the optional is nil. We should try to avoid it.A common example of implicitly unwrapped optionals is how view controller define their IBOutlets.
It would be unwieldy(笨重的) to always unwrap each view outlet inside view controllers.
#question mark, exclamation mark, unwrapping
11.1 Optional Chain
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil. If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil, the property, method, or subscript call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully if any link in the chain is nil.
12. NSKeyedArchiver
Core data, NSKeyedArchiver and UserDefaults are three ways in which a programmer can persist data in between app launches. Though core data is slightly more complicated, it is useful when the stored information requires structure. NSKeyedArchiver is less complex and slower than core data, but is much simpler to use. UserDefaults is the simplest method to persist data.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.
簡單來說:
keep private details of a class hidden from the rest of the app
keep internal details of a framework hidden from the client app
17. UIViewcontroller lifecircle
A singleton class returns the same instance no matter how many times an application requests it. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.
use the @synchronized pattern - and @synchronized is still the best way to do simple locking in Objective-C.
19. Closures
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
20. Autolayout
Auto Layout dynamically calculates the size and position of all the views in your view hierarchy(階層), based on constraints placed on those views.
21. Safe area
The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. After iOS11, you can use SafeAreaLayoutGuide. By add constraints between your content and safe area anchors. This prevents your content from being obscured(模糊, 遮擋) by top and bottom bars.
It will crash, because you release twice.
2. What is category in Obj-c?
A category is a way to add methods to existing classes.
4. Why don't we use strong for enum property in Obj-c?
Because enum aren't objects, so we don't specify strong or weak here.
5. @synthesize and @dynamic keyword.
@synthesize - tell compiler to synthesize(合成, 整合) getter and setter methods for your property.
@dynamic - tell the compiler that getter and setter are implemented not by the class itself but somewhere else like the superclass or will be provided at runtime.
6. Why do we use @synchronized?
In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you.
13. Access Control
Open access and public access enable entities to be used within any source file from their defining module, and also in a source file from another module that imports the defining module. You typically use open or public access when specifying the public interface to a framework. The difference between open and public access is described below:- An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.
- A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module.
Internal access enables entities to be used within any source file from their defining module, but not in any source file outside of that module. You typically use internal access when defining an app’s or a framework’s internal structure.
File-private access restricts the use of an entity to its own defining source file. Use file-private access to hide the implementation details of a specific piece of functionality when those details are used within an entire file.
Private access restricts the use of an entity to the enclosing declaration, and to extensions of that declaration that are in the same file. Use private access to hide the implementation details of a specific piece of functionality when those details are used only within a single declaration.
Open access is the highest (least restrictive) access level and private access is the lowest (most restrictive) access level.
簡單來說:
keep private details of a class hidden from the rest of the app
keep internal details of a framework hidden from the client app
14. What is Core Data?
Core Data is a framework for managing an object graph. An object graph is nothing more than a collection of interconnected objects.
Core Data is not a database.
Core Data is not a database.
Core Data isn't thread safe. Core Data expects to be run on a single thread.
How to use it?
When you start a new project in Xcode and open the template selection dialog, select the Use Core Data checkbox. A source file for the Core Data model is created as part of the template. That source file will have the extension .xcdatamodeld. Select that file in the navigator area to display the Core Data model editor.
1. open new project and check with "use Core Data"
2. open file have extension .xcdatamodelid, then xcode will display Cor Data model editor.
3. create entity and create attributes and relationships for the entity.
4. use NSManagedObject to manage data. (NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store.)
5. NSFetchRequest is the class responsible for fetching from Core Data.
15. What is Grand Central Dispath(GCD)?
GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. A queue is actually a block of code that can be executed synchronously or asynchronously, either on the main or on a background thread. Queues are following the FIFO pattern.
Another important concept is the work item. A work item is literally a block of code that is either written along with the queue creation, or it gets assigned to a queue and it can be used more than once (reused).
When to Go for GCD or NSOperation?
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD.
16. What is different between Frame and Bounds?
frame = a view's location and size using the parent view's coordinate system.(relative to the superview)
Important for: placing the view in the parent
bounds = a view's location and size using its own coordinate system
Important for: placing the view's content or subviews within itself
15. What is Grand Central Dispath(GCD)?
GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. A queue is actually a block of code that can be executed synchronously or asynchronously, either on the main or on a background thread. Queues are following the FIFO pattern.
Another important concept is the work item. A work item is literally a block of code that is either written along with the queue creation, or it gets assigned to a queue and it can be used more than once (reused).
When to Go for GCD or NSOperation?
when you want more control over queue (all above mentioned) use NSOperation and for simple cases where you want less overhead (you just want to do some work "into the background" with very little additional work) use GCD.
16. What is different between Frame and Bounds?
frame = a view's location and size using the parent view's coordinate system.(relative to the superview)
Important for: placing the view in the parent
bounds = a view's location and size using its own coordinate system
Important for: placing the view's content or subviews within itself
17. UIViewcontroller lifecircle
ViewDidLoad
- Called when you create the class and load from xib. Great for initial setup and one-time-only work. It might be called several times if the view is unloaded due to low memory and then loaded again.ViewWillAppear
- Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.ViewDidAppear
- Called after the view appears - great place to start an animations or the loading of external data from an API.ViewWillDisappear
/DidDisappear
- Same idea asViewWillAppear
/ViewDidAppear
.
A singleton class returns the same instance no matter how many times an application requests it. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.
use the @synchronized pattern - and @synchronized is still the best way to do simple locking in Objective-C.
19. Closures
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
20. Autolayout
Auto Layout dynamically calculates the size and position of all the views in your view hierarchy(階層), based on constraints placed on those views.
21. Safe area
The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. After iOS11, you can use SafeAreaLayoutGuide. By add constraints between your content and safe area anchors. This prevents your content from being obscured(模糊, 遮擋) by top and bottom bars.
Objective-C PART
1. What happen in this code(release twice)?
Obj * obj = [[[Obj create] autorelease] autorelease];It will crash, because you release twice.
2. What is category in Obj-c?
A category is a way to add methods to existing classes.
3. Whis is made up of NSError object?
There are 3 parts of NSError object: a domain, an error code, and a user info dictionary.
The domain is a string that indentifies what categories of errors.
User info dictionary may also provide localized error descriptions
4. Why don't we use strong for enum property in Obj-c?
Because enum aren't objects, so we don't specify strong or weak here.
5. @synthesize and @dynamic keyword.
@synthesize - tell compiler to synthesize(合成, 整合) getter and setter methods for your property.
@dynamic - tell the compiler that getter and setter are implemented not by the class itself but somewhere else like the superclass or will be provided at runtime.
6. Why do we use @synchronized?
In Objective-C, a @synchronized block handles locking and unlocking (as well as possible exceptions) automatically for you.
0 comments: