IOS Interview Questions and answers

Source: Internet
Author: User

IOS Interview Questions and answers

 

  1. 1. WriteNSStringClass implementation

    + (Id) initWithCString :( c ***** t char *) nullTerminatedCString encoding :( NSStringEncoding) encoding;

    + (Id) stringWithCString: (c ***** t char *) nullTerminatedCString

    Encoding: (NSStringEncoding) encoding

    {

    NSString * obj;

    Obj = [self allocWithZone: nsdefamalmalloczone ()];

    Obj = [obj initWithCString: nullTerminatedCString encoding: encoding];

    Return AUTORELEASE (obj );

    }

    2StaticKeyword:

    (1) The static variable in the function body applies to this function body. Unlike the auto variable, the memory of this variable is allocated only once,

    Therefore, the value remains the value of the previous time during the next call;

    (2) The static global variables in the module can be accessed by the functions used in the module, but cannot be accessed by other functions outside the module;

    (3) The static function in the module can only be called by other functions in the module. The scope of use of this function is limited in the Declaration.

    In its module;

    (4) static member variables in the class belong to the entire class and only one copy of all objects in the class;

    (5) The static member function in the class belongs to the whole class. this function does not receive the this pointer, so it can only be a static member variable of the category.

    3. Differences and connections between threads and processes?

    Processes and threads are the basic units for running programs that the operating system understands. The system uses this basic unit to realize the system's concurrency for applications.

    The main difference between processes and threads is that they are different operating system resource management methods. A process has an independent address space. After a process crashes, it will not affect other processes in the protection mode, but the thread is only a different execution path in the process. A thread has its own stack and local variables, but there is no separate address space between threads. If a thread dies, the whole process dies. Therefore, multi-process programs are more robust than multi-threaded programs, however, during process switching, resources are consumed and the efficiency is lower. But for some concurrent operations that require simultaneous and shared variables, you can only use threads, not processes.

    4. Stack and stack differences

    Management Method: For stacks, it is automatically managed by the compiler without manual control. For heaps, the release work is controlled by programmers and memory leak is easily generated.

    Application size:

    STACK: in Windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In WINDOWS, the stack size is 2 MB (OR 1 MB, in short, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow will be prompted. Therefore, the space available from the stack is small.

    Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

    Fragmentation problem: for the heap, frequent new/delete operations will inevitably lead to memory space disconnections, resulting in a large number of fragments, reducing program efficiency. For the stack, this problem will not exist, because the stack is an advanced and outgoing queue, they are so one-to-one correspondence, it is impossible to have a memory block popped up from the middle of the stack.

    Allocation Method: The heap is dynamically allocated without static allocation. There are two stack allocation methods: static allocation and dynamic allocation. Static allocation is completed by the compiler, such as local variable allocation. Dynamic Allocation is implemented by the alloca function, but the stack dynamic allocation is different from the heap dynamic allocation. Its Dynamic Allocation is released by the compiler without manual implementation.

    Allocation Efficiency: the stack is the data structure provided by the machine system, and the computer will provide support for the stack at the underlying layer: allocate a dedicated register to store the stack address, the output stack of the Pressure Stack has dedicated Command Execution, which determines the high efficiency of the stack. The heap is provided by the C/C ++ function library, and its mechanism is very complicated.

    5. What is a key?-Value,What is the Key Path?

    The nature of the model is specified by a simple key (usually a string. The view and controller use keys to find the corresponding attribute values. In a given object, all values of the same attribute have the same data type. Key-value encoding technology is used for such a search-it is a mechanism for indirect access to object attributes.

    A key path is a string consisting of keys separated by vertices. It is used to specify a sequence of object properties connected together. The

    The nature is determined by the previous nature, and the value of each key is also relative to the previous nature. The Key Path allows you to use

    The implementation method specifies the properties of related objects. Through the Key Path, you can specify a path in any depth in the object graph to point it to

    Specify the attributes of an object.

    6 goals-Action Mechanism

     

    The target is the receiver of the action message. A widget, or more commonly its unit, uses Socket variables (see "socket variables" Section)

    To retain the target of the action message.

    An action is a message sent from the control to the target, or from the perspective of the target, it is a method implemented by the target to respond to the action.

    Programs need some mechanisms to translate events and commands. This mechanism is the target-action mechanism.

    7ObjcMemory Management

    ?? If you create an object by allocating and initializing (for example, [MyClass alloc] init ]),

    With this object, you need to release it. This rule also applies when using NSObject's convenient method new.

    ?? If you copy an object and you have the Copied object, you must release the object.

    ?? If you keep an object, you have some of it, and you need to release it when it is no longer in use.

    Conversely,

    ?? If you receive an object from another object, you do not own this object or release it (this rule has a few

    ).

     

     

    8. What is the automatic release pool?,How to work

    When you send an autorelease message to an object, Cocoa puts a reference of this object into the latest Auto Release pool. It is still a legitimate object, so other objects in the scope defined by the automatic release pool can send messages to it. When the program is executed at the end of the scope, the automatically released pool will be released, and all objects in the pool will be released.

    1. ojc-c manages the memory by using a "referring counting" (reference count) method. When an object starts to allocate memory (alloc), the reference count is one, in the future, when there is a copy or retain, the reference count will be added. When the release and autorelease parameters are met, the reference count will be reduced by one. If the Count of this object is changed to 0, will be destroyed by the system.

    2. The NSAID utoreleasepool is used to manage the reference count. You don't need to worry about this.

    3. There is no difference between autorelease and release, but the timing for reducing the reference count by one is different. autorelease will reduce the reference count by one when the object is actually used.

    What are the nine factory methods?

    The implementation of the class factory method is to provide convenience to customers. They combine allocation and initialization in one step, return the created object, and

    For automatic release. These methods are in the form of + (type) className... (className does not include any prefix ).

    The factory method may not only be used for convenience. They can not only combine allocation and initialization, but also provide

    Image allocation information.

    Another purpose of the class factory method is to make the class (such as NSWorkspace) provide a single-piece instance. Although the init... method can be confirmed by

    Each time the program runs, only one instance exists. However, it must first allocate a "generated" instance and then release the instance.

    The factory method can avoid blind memory allocation for objects that may not be used.

    10. What is a single-piece instance?

    Some classes in the Foundation and Application Kit frameworks only allow the creation of single-piece objects, that is, the unique instances of these classes in the current process. For example, the NSFileManager and NSWorkspace classes are used to instantiate single-piece Objects Based on processes. When you request instances of these classes, they will pass you a single instance reference. If the instance does not exist, the instance is allocated and initialized first. A single-piece object acts as a control center and is responsible for guiding or coordinating various services. If the class has only one instance (for example

    NSWorkspace), you should generate a single-piece instance, instead of multiple instances. If you may have multiple instances one day in the future, you can

    To use a single-piece instance mechanism, rather than a factory method or function.

    11 dynamic binding

    -Determine the method to be called at runtime

     

    Dynamic binding also delays the confirmation of the call Method to the runtime. During compilation, the method call is not bound with the Code. The called code is confirmed only after the message is sent out. Through dynamic type and dynamic binding technology, your code can get different results every time you execute it. The runtime factor is used to determine the message receiver and the called method. The message distribution mechanism at runtime provides support for dynamic binding. When you send a message to an object with a dynamic type, the runtime environment system locates the class of the object through the isa pointer of the receiver and determines the called method starting from this, methods and messages are dynamically bound. Additionally, you can automatically obtain the benefits of dynamic binding without having to do any work in Objective-C code. Each time you send a message,

     

    In particular, when the message receiver is an object of the dynamic type, dynamic binding will occur routinely and transparently.

    12Obj-cAdvantages and disadvantages

    Advantages of objc:

    1) Cateogies

    2) Posing

    3) Dynamic Identification

    4) indicator calculation

    5) elastic message transmission

    6) Not an overly complex C-derivative Language

    7) Objective-C and C ++ Mixed Programming

    Disadvantages:

    1) namespaces are not supported.

    2) Operator Overloading is not supported.

    3) Multi-inheritance is not supported.

    4) use the dynamic runtime type. All methods are called by functions, so many compilation optimization methods are not used. (Such as inline functions), poor performance.

    13Sprintf, strcpy, memcpyWhat should I pay attention to when using it?

    Strcpy is a string copy function. Its prototype is strcpy (char * dst, c *** t char * src );

    Copy a string starting with src to the memory starting with dst, And the ending sign is '\ 0'. Because the copy length is not controlled by ourselves, therefore, this string copy is prone to errors. Memcpy is a memory copy function. Its prototype is memcpy (char * dst, c ***** t char * src, unsigned int len );

    Copy a piece of memory with a length of len from src to dst. The length of this function is controllable. However, memory overlay may occur.

    Sprintf is a Formatting Function. Format a piece of data into a string buffer using a specific format. The length of the sprintf formatted function is uncontrollable. It is possible that the formatted string will exceed the buffer size, resulting in overflow.

    14. Answer:

    A) int a; // An integer

    B) int * a; // A pointer to an integer

    C) int ** a; // A pointer to a pointer to an integer

    D) int a [10]; // An array of 10 integers

    E) int * a [10]; // An array of 10 pointers to integers

    F) int (* a) [10]; // A pointer to an array of 10 integers

    G) int (* a) (int); // A pointer to a function a that takes an integer argument and returns an integer

    H) int (* a [10]) (int); // An array of 10 pointers to functi ***** that take an integer argument and return an integer

    15. Readwrite,Readonly,Assign,Retain,Copy,NonatomicRole of attributes

    @ Property is an attribute access statement. The extension number supports the following attributes:

    1, getter = getterName, setter = setterName, set the method names of setter and getter

    2, readwrite, readonly, set the available access level

    2. The assign and setter Methods assign values directly without any retain operations. To solve the problem of the original type and cycle reference

    3. The retain and setter Methods perform the release old value for the parameter and retain the new value. All implementations are in this Order (relevant information is available on CC)

    4. copy and setter Methods perform the Copy operation. Like the retain process, the old value is release first, and then the new object is copied. retainCount is 1. This is a mechanism introduced to reduce context dependencies.

    Copy is used when you do not want a and B to share a piece of memory. A and B each have their own memory.

    5. nonatomic: Non-atomic access without synchronization. multi-thread concurrent access improves performance. Note: If this attribute is not added, both access methods are atomic transaction access by default. The lock is added to the instance level of the object to which it belongs (I understand it so well ...).

    Atomic and nonatomic are used to determine whether the getter and setter generated by the compiler are atomic operations. In a multi-threaded environment, atomic operations are necessary; otherwise, errors may occur. With atomic added, the setter function will become as follows:

    16 when is delegate used and Notification used? A: delegate is for the one-to-one relationship, and the reciever can return the value to the sender. The notification can be for one-to-one/pull/none, and the reciever cannot return the value to the sender. therefore, delegate is used by sender to receive a function feedback value from reciever, and notification is used to notify multiple objects of an event.

    17 What are KVC and KVO? A: KVC (Key-Value-Coding) internal implementation: when an object calls setValue, (1) first, find the environment parameters required for running the method based on the method name. (2) he will use his isa pointer to combine environment parameters to find the specific method to implement the interface. (3) directly find the specific method implementation. KVO (Key-Value-Observing): When the observer registers an object's attribute and the isa pointer of the observed object is modified, the isa Pointer Points to an intermediate class, instead of real classes. Therefore, the isa pointer does not need to point to the real class of the Instance Object. Therefore, our program should not depend on the isa pointer. When calling a class method, it is best to specify the Class Name of the object instance.

    When is the loadView, viewDidLoad, and viewDidUnload of 18 viewcontroller called? What should I do in the Custom ViewController functions? A: viewDidLoad is called when the view is initialized from the nib file, while loadView is called when the controller's view is nil. This method is called when the view is programmed. By default, the view controller registers the memory warning notification. When any view of the view controller is useless, viewDidUnload is called, here, we implement retain's view release. If it is retain's IBOutlet view attribute, we should not release it here, and IBOutlet will be responsible for release.

    19

    "NSMutableString *" indicates the "NSMutableString" object, which is different from each other.

    NSString is just a pointer to an object.

    Process-oriented is to analyze the steps required to solve the problem, and then use functions to implement these steps Step by step. You can call these steps one by one.

    Object-oriented refers to dividing a problem transaction into various objects. The object is created not to complete a step, but to describe the behavior of a thing in the whole process of solving the problem .;

    20 categories

    Category has three main functions:

    (1) Distribute the implementation of classes to multiple different files or different frameworks.

    (2) create a forward reference to a private method.

    (3) add informal protocols to objects.

    CATEGORY limitations

    There are two limitations:

    (1) You cannot add new instance variables to the class. The class does not have a location to accommodate instance variables.

    (2) name conflict, that is, when the method in the category conflicts with the original class method name, the category has a higher priority. The category method will completely replace the initial method so that the initial method cannot be used.

    The limitations of being unable to add instance variables can be solved using dictionary objects.

    21 what does the keyword volatile mean? Three different examples are provided:

    A variable defined as volatile means that this variable may be unexpectedly changed, so that the compiler will not assume the value of this variable. Specifically, the optimizer is in use

    This variable must be carefully re-read every time, instead of using the backup stored in the register. The following are examples of volatile variables:

    ? Hardware registers of parallel devices (for example, Status Registers)

    ? Non-automatic variables accessed in an interrupt service subroutine)

    ? Variables shared by several tasks in multi-threaded applications

     

    ? Can a parameter be const or volatile? Explain why.

    ? Can a pointer be volatile? Explain why.

     

     

    The answer is as follows:

    ? Yes. One example is read-only status registers. It is volatile because it may be unexpectedly changed. It is const because the program should not try to modify it.

    ? Yes. Although this is not very common. One example is when a service subroutine repairs a pointer to a buffer.

    22 @ synthesize: The getter and setter attributes are automatically generated by the system.

    @ Dynamic is the property declaration provided by the developer.

    @ Dynamic refers to the Code provided by developers: setter is required for read-only attributes, and setter and getter are required for read/write attributes. @ Synthesize indicates that, unless the developer has already done this, the compiler generates the corresponding code to satisfy the attribute declaration.

    After reading some documents, confirm @ dynamic to tell the compiler that the methods for obtaining and assigning attributes are implemented by the user and are not automatically generated.

    23 Difference between shallow copy and deep copy?
    What is the difference between shallow replication and deep replication?
    Answer: copy the pointer to the object instead of the referenced object.
    Deep replication: Copies the referenced object itself.
    That is to say, I have an object A. After copying A copy and getting the_copy object, for the shortest copy, A and A_copy point to the same memory resource, and the copy is just A pointer, object Resource
    There is only one copy. If we perform the modification operation on A_copy, we will find that the object referenced by A is also modified, which violates the idea of copying. Deep replication is easy to understand, and memory exists
    Two independent objects.
    The popular words on the Internet will be:
    Copying is like a shadow between you and you. You are finished, and your shadow is finished.
    Deep replication is like cloning you and your clone. You are finished and your clone is still alive.

    24 What is advantage of categories? What is difference between implementing a category and inheritance?
    What is the role of a category? What are the differences between inheritance and category implementation?
    Answer: you can add a new method to the category without learning or changing the original code. You can only add the method, but cannot delete the modification.
    In addition, if the category conflicts with the method in the original class, the category overwrites the original method because the category has a higher priority.
    Category has three main functions:
    (1) Distribute the implementation of classes to multiple different files or different frameworks.
    (2) create a forward reference to a private method.
    (3) add informal protocols to objects.
    Inheritance can be added, modified, or deleted, and attributes can be added.

    25. Difference between categories and extensions?
    The differences between category and class extension.
    Answer: The difference between category and extensions is that the latter can add attributes. In addition, the method added by the latter must be implemented.
    Extensions can be considered as a private Category.

    26. Difference between protocol in objective c and interfaces in java?
    What is the difference between the Protocol in oc and the interface concept in java?
    Answer: The agent in OC has two meanings: formal and informal protocol. The former is the same as the Java interface.
    The methods in informal protocol belong to the scope of design pattern Consideration and are not required. However, if there is an implementation, the attributes of the class will be changed.
    In fact, I have read about formal protocols, types, and informal protocols a long time ago and have written them in the course of study.
    "The concept of informal protocols is actually another expression of categories." Here are some methods you may want to implement. You can use them to better complete the work ".
    This means that these are optional. For example, if we want a better method, we will declare such a category to implement it. Then you can directly use these better methods later.
    In this case, we always think the category is a bit like an optional protocol. "
    Now we can see that protocal has begun to unify and standardize the two, because the document says "informal protocols use interface modifier",
    Now we can see two modifiers in the Protocol: "must be implemented (@ requied)" and "optional implementation (@ optional )".

    26 What are KVO and KVC?
    Answer: kvc: Key-value encoding is an indirect access object attribute that uses a string to identify the attribute, instead of calling an access method, or directly accessing the attribute through instance variables.
    In many cases, program code can be simplified. The apple documentation provides a good example.
    Kvo: the key-value observation mechanism. It provides a method to observe the changes of a certain attribute, greatly simplifying the code.
    You can see that one of the places you have used is monitoring the status of button click changes.
    For example, a Custom button
    [Cpp]
    [Self addObserver: self forKeyPath: @ "highlighted" options: 0 context: nil];
    # Pragma mark KVO
    -(Void) observeValueForKeyPath :( NSString *) keyPath ofObject :( id) object change :( NSDictionary *) change context :( void *) context
    {
    If ([keyPath isw.tostring: @ "highlighted"]) {
    [Self setNeedsDisplay];
    }
    }

    In theory, the system changes the value obtained based on keypath, which is the same as the kvc mechanism.
    How to find the value through the key of the kvc mechanism:
    "When calling an object through KVC, for example, [self valueForKey: @" someKey "], the program will automatically try to parse the call in several different ways. First, check whether the object has the someKey method. If it is not found, it will continue to find whether the object has the someKey instance variable (iVar). If it has not been found, the program will continue to try to call-(id) valueForUndefinedKey: This method. If this method is still not implemented, the program will throw an NSUndefinedKeyException error.
    (Cocoachina.com Note: When the Key-Value Coding search method is used, it not only searches for the someKey method, but also the getsomeKey method. A get is added to the front, or _ someKey and _ getsomeKey. In addition, when searching for instance variables, we will not only look for the someKey variable, but also find whether the _ someKey variable exists .)
    Design valueForUndefinedKey: when you use the-(id) valueForKey method to request a value from an object, the object can have a final chance to respond to the request before an error occurs. There are many benefits to doing so. The following two examples illustrate the benefits of doing so. "
    Come to cocoa, this statement should be quite reasonable.
    Because we know that there is a highlighted instance variable in the button, we just need to add a related keypath,

    27 What is purpose of delegates?
    What is the role of proxy?
    Answer: The proxy aims to change or transmit the control chain. Allows a class to notify other classes at certain times without obtaining pointers to those classes. This reduces the complexity of the framework.
    In addition, the proxy can be understood as a similar callback listening mechanism in java.

    28 What are mutable and immutable types in Objective C?
    Types that can be modified or not modified in oc.
    Answer: you can modify unchangeable collection classes. In my personal understanding, dynamic addition and modification are the same as dynamic addition and modification.
    For example, NSArray and NSMutableArray. The former memory control after Initialization is fixed and immutable, and the latter can be added, and new memory space can be dynamically applied.

    29 When we call objective c is runtime language what does it mean?
    What do we mean when oc is a dynamic runtime language?
    Answer: polymorphism. It mainly delays the determination of data types from compilation to runtime.
    This problem actually involves two concepts: runtime and polymorphism.
    Simply put, the runtime determines the class of an object and calls the specified method of the Class Object until it is run.
    Polymorphism: the ability of different objects to respond to the same message in their own way is called polymorphism. This means that we assume that biological classes (life) use the same method-eat;
    Humans belong to creatures, and pigs also belong to creatures. After they all inherit life, they implement their own eat. However, we only need to call their own eat methods.
    That is, different objects respond to the same message in their own way (response to the eat selector ).
    Therefore, we can also say that the runtime mechanism is the basis of polymorphism ?~~~

    30 what is difference between NSNotification and protocol?
    What are the differences between notifications and protocols?
    Answer: The Protocol has a control link (has-a). No notification is sent.
    First of all, I didn't quite understand what a control chain is ~). However, we can understand the behavior patterns of notifications and proxies in a simple analysis.
    To put it simply, a notification can be one-to-multiple, and one message can be sent to multiple message recipients.
    According to our understanding, agents do not directly say that they cannot be one-to-many. For example, if we know a celebrity economic representative, a single economic person is often responsible for the affairs of Several stars.
    It is only for different stars that the agent objects are different and correspond to each other. It is impossible to say that A star needs to handle A press conference tomorrow. After the agent sends A message to handle the press conference, B's
    The press conference was launched. But the notification is different. He only cares about sending the notification, but does not care about how many notifications he is interested in.
    Therefore, the control chain (has-a) roughly shows the correspondence between a single ownership and a controllable English word.

     

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.