Some common questions and answers in OC

Source: Internet
Author: User
Tags variable scope

1. Do object-c have multiple inheritance? What's the substitute for nothing? All classes in cocoa are subclasses of NSObjectmulti-inheritance is implemented here using the Protocol principal agent .you do not have to consider the concept of a cumbersome multi-inheritance, virtual base class.The polymorphic properties of Ood are implemented by delegates in Obj-c. 2. Does Object-c have a private method? What about private variables? There are only two methods in the Objective-c– class, static methods and instance methods. This does not seem to be a complete object-oriented one, and the principle of OO is that an object exposes only useful things. If you don't have a private method, it's not easy for some small-scale code reuse. Fame a private method inside a class@interface controller:nsobject {nsstring *something;}+ (void) Thisisastaticmethod;– (void) Thisisaninstancemethod;@end@interface Controller (private)-(void) Thisisaprivatemethod;@end@private can be used to modify private variablesin Objective‐c, all instance variables are private by default, and all instance methods are public by default 3. What does the keyword const mean?const means "read-only," what does the following declaration mean? const int A;int const A;const int *a; (A is a pointer to the number of constant integers)int * const A; (const A is a pointer, that is, constant A is a pointer to an integral number)INT const * a const;the first two functions are the same, a is a constant integer number. The third means that a is a pointer to a constant integer number (that is, the integer number is not modified by assigning a value to *a, but pointer a can be modified to point to another constant integer). The fourth meaning of a is a constant pointer to an integer number (that is, the integer number pointed to by the pointer can be modified by assigning a value to *a, but the constant pointer A is not modifiable). The last one means that a is a constant pointer to a constant number (that is, the integer number pointed to by the pointer is not modifiable and the pointer is not modifiable). Conclusion:• The role of the keyword const is to convey very useful information to the person who is reading your code, in fact, declaring that a parameter is constant in order to tell the user the purpose of the application of this parameter. Ifyou've spent a lot of time cleaning up the rubbish left by other people, and you'll soon learn to thank for the extra information. (Of course, programmers who know how to use a const programmer seldom leave rubbish for others to clearManagement. )• By giving some additional information to the optimizer, using the keyword const may produce more compact code. • Rational use of the keyword const allows the compiler to naturally protect those parameters that you do not want to change, and prevent them from being unintentionally modified by the code. In short, this can reduce the occurrence of bugs. to prevent a variable from being changed, you can use the Const keyword. When defining this const variable, it is often necessary to initiallystart, because there will be no chance to change it again;(2) for pointers, you can specify that the pointer itself is const, or that the data that the pointer refers to is const, or bothfixed as const;(3) In a function declaration, the const can modify the formal parameter, indicating that it is an input parameter, the value cannot be changed inside the function;(4) for a class member function, if it is specified as a const type, it indicates that it is a constant function and cannot modify the member variables of the class;(5) for a member function of a class, sometimes it is necessary to specify that its return value is a const type so that its return value is not "left value".  4. What does the keyword volatile mean? And give three different examples? A variable that is defined as volatile means that the variable may be unexpectedly changed so that the compiler does not assume the value of the variable. Precisely, the optimizer is using theThis variable must be carefully re-read the value of the variable every time, rather than using the backup stored in the register. Here are a few examples of volatile variables:• Hardware registers for parallel devices (e.g., status registers)• Non-automatic variables that are accessed in an interrupt service subroutine (non-automatic variables)• Variables shared by several tasks in multi-threaded applications• Can a parameter be either const or volatile? explain why. • Can a pointer be volatile? explain why. Here's the answer:• Yes. An example is a read-only status register. It is volatile because it can be changed unexpectedly. It is const because the program should not attempt to modify it. • Yes. Although this is not very common. An example is when a service subroutine fixes a pointer that points to a buffer.  5. Static effect? The function body static variable scope is the function body, differs from the auto variable, the memory of the variable is allocated only once,therefore, its value remains the last value at the next call;(2) The static global variable within the module can be accessed by functions used within the module, but not by other functions outside the module;(3) The static function within the module can only be called by other functions within this module, and the use of this function is limited to the declarationwithin its module;(4) A static member variable in a class is owned by the entire class and has only one copy of all objects of the class;(5) The static member function in a class is owned by the entire class, which does not receive the this pointer, and therefore can only access static member variables of the class.  6. #import和 The difference between # include, what does @class represent? @class is commonly used in header files to declare an instance variable of the class, and in M files it is necessary to use #importand #import's advantage over # include is that it doesn't cause duplicate inclusions 7. What are the differences between threads and processes? processes and threads are the basic units that the operating system realizes, and the system uses this basic unit to realize the concurrency of the system to the application. The main difference between processes and threads is that they are different ways to manage operating system resources. The process has a separate address space, and after a process crashes, it does not affect other processes in protected mode, and the thread is just a different execution path in a process. Thread has its own stack and local variables, but there is no separate address space between the threads, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs, but in the process of switching, the cost of large resources, efficiency is worse. But for some concurrent operations that require simultaneous and shared variables, only threads can be used, and processes cannot be used.  8. What is the difference between heap and stack? Management mode: For the stack, is automatically managed by the compiler, without our manual control, for the heap, the release of work by the programmer control, easy to produce memory leak. Application Size:stack: Under Windows, the stack is the data structure to the low address extension, which is a contiguous area of memory. This sentence means that the top of the stack of the address and the maximum capacity of the stack is the system pre-defined, in Windows, the size of the stack is 2M (also said 1M, in short, is a compile-time determination of the constant), if the request for more space than the stack's remaining space, will prompt overflow. Therefore, the space available from the stack is small. Heap: A heap is a data structure that extends to a high address, and is a discontinuous area of memory. This is because the system is stored with a linked list of free memory address, is naturally discontinuous, and the chain of the list of traversal direction is from the low address to high address. The size of the heap is limited by the valid virtual memory in the computer system. Thus, the space of the heap is more flexible and relatively large. fragmentation problem: For the heap, frequent new/delete is bound to cause memory space discontinuity, resulting in a large number of fragments, so that program efficiency is reduced. For the stack, there is no problem, because the stack is advanced out of the queue, they are so one by one correspondence, so that there will never be a memory block from the middle of the stack poppedallocation method: The heap is dynamically allocated and there are no statically allocated heaps. Stacks are allocated in 2 ways: static allocation and dynamic allocation. Static allocations are done by the compiler, such as the allocation of local variables. The dynamic allocation is assigned by the ALLOCA function, but the dynamic allocation of the stack is different from the heap, and his dynamic allocation is released by the compiler without our manual implementation. allocation efficiency: The stack is the data structure provided by the machine system, the computer will support the stack at the bottom: allocate the address of the special register storage stack, the stack stack has a special instruction execution, which determines the efficiency of the stack is high. The heap is provided by the C + + function library, and its mechanism is very complex.  9. Object-c memory management? 1. When you create an object using the New,alloc and copy methods, the object's retention counter value is 1. When you no longer use the object, you are responsible for sending a release or Autorelease message to the object. This will destroy the object at the end of its useful life. .2. When you obtain an object by any other means, assuming that the object has a retention counter value of 1 and has been set to auto-release, you do not need to do anything to ensure that the object is cleaned up. If you intend to have the object for a period of time, you need to keep it and make sure that it is released when the operation is complete.3. If you keep an object, you need to (eventually) release or release the object automatically. You must keep the Retain method and the release method equal in number of times. 10. Why are the properties of many built-in classes, such as Tableviewcontroller delegate, assign not retain? All reference counting systems have problems with cyclic applications. For example, the following reference relationship:   ·    object A was created and referenced to object b.   ·    object B was created and referenced to object c.   ·  &NB SP; object C is created and referenced to Object B. At this time, the reference counts for B and C are 2 and 1, respectively. When a no longer uses B, the call release releases the ownership of B, because C also references B, so the reference count for B is 1,b and will not be freed. B is not released, the reference count of C is 1,c and will not be released. From then on, B and C remain in memory forever. In this case, the circular reference must be interrupted and the reference relationship maintained through other rules. For example, our common delegate is often a property of the Assign mode rather than the Retain method, and the assignment does not increase the reference count to prevent unnecessary circular references on both sides of the delegation. If a Uitableviewcontroller object a acquires ownership of UITableView object B through retain, the delegate of this UITableView object B is a, and if this delegate is retain mode, There's basically no chance of releasing these two objects. You should also be aware of this when designing your delegate model. 11. When defining attributes, what is the use of copy, assign, retain? Assign is used for simple data types such as Nsinteger,double,bool,retain and copy for objects, and copy is used when a points to an object, B also wants to point to the same object, if the Assign,a is released, then B is crash, If you use Copy, A and b each have their own memory, you can solve the problem. Retain will add one to the counter, can also solve the problem of assign. Additionally: Atomic and nonatomic are used to determine whether the getter and setter generated by the compiler are atomic operations. In a multithreaded environment, atomic operations are necessary, otherwise they may cause incorrect results. Adding the Atomic,setter function will change to the following: if (Property! = newvalue) {[Property release];p roperty = [newvalue retain];}  12. When was the object being release? The reference count is 0 o'clock. Autorelease actually just delayed the call to release, and for each autorelease, the system simply placed the object in the current Autorelease pool, and when the pool was released, All object in the pool is called release. For each runloop, the system implicitly creates a autorelease pool so that all the release pool forms a callstack-like stack, at the end of each runloop, the current stack top autorelease The pool will be destroyed so that every object in the pool (which is the Autorelease object) will be release. So what is a runloop? A UI event, Timer call, delegate call, will be a new runloop 13.ios is there a garbage collection? OBJECTIVE-C 2.0 also has a garbage collection mechanism, but it can only be used in versions of Mac OS X Leopard 10.5 or more. The reuse mechanism of  14.tableview? Viewing the UITableView header file, you will find nsmutablearray*  visiablecells, and nsmutabledictnery* reusabletablecells two structures.  Save the cells,reusabletablecells cells that are currently displayed in Visiablecells. At the beginning of TableView display, Reusabletablecells is empty, then TableView Dequeuereusablecellwithidentifier:cellidentifier returns nil. The starting cell is created by [[UITableViewCell alloc] Initwithstyle:uitableviewcellstyledefault Reuseidentifier:cellidentifier],  And Cellforrowatindexpath just calls the maximum number of cells to display. For example: There are 100 data, iphone one screen display up to 10 cells. The program initially shows TableView in the case of: 1, with [[UITableViewCell alloc] Initwithstyle:uiTableviewcellstyledefault Reuseidentifier:cellidentifier] Creates 10 cells and assigns the same reuse identity to the cell (of course, you can specify different identities for cells of different display types). And all 10 cells are added to the Visiablecells array, and the Reusabletablecells is empty. 2, drag down TableView, when cell1 completely out of the screen, and CELL11 (it is also alloc out, the reason above) is fully displayed. Cell11 joins to Visiablecells,cell1 to move out visiablecells,cell1 to join to Reusabletablecells. 3. Then drag the TableView down, because there are already values in the reusabletablecells, so when it is necessary to show that the new Cell,cellforrowatindexpath is called again, TableView Dequeuereusablecellwithidentifier:cellidentifier, return to CELL1. Cell1 joins the VISIABLECELLS,CELL1 to move out of the reusabletablecells;cell2 to move out visiablecells,cell2 join to Reusabletablecells. Cells that need to be displayed later can be reused normally. When are  15.viewcontroller's Loadview, Viewdidload, and Viewdidunload called, and what should be done in these functions when customizing Viewcointroller? By Init, Loadview, Viewdidload, Viewdidunload, Dealloc's relationship The Init method initializes the necessary objects in the Init method (in accordance with Lazyload thought) Init method to initialize the Viewcontroller itself Loadview method when the view needs to be displayed and it is nil, The method is called by the Viewcontroller. Do not call the method directly. If you manually maintain views, you must override this method if you use IB to maintain views, you must not overload override the method Loadview and IB build view you implement the Loadview method in the controller, then you may be called by memory management control at some point when the application is running. If the device is running low on memory, the view controller receives the DidreceivememorYwarning's message. The default implementation is to check whether the current controller's view is in use. If its view is not inside the view hierarchy currently in use and your controller implements the Loadview method, the view will be release and the Loadview method will be re-used to create a new view. The Viewdidload method Viewdidload This method is called only when the view is initialized from the nib file. Overloads override this method to further customize the view in iphone OS 3.0 and later versions, You should also overload the override Viewdidunload to release any index viewdidload to the view after you call the data Modelviewdidunload method when the system memory is tight (note: Viewcontroller is not dealloc) when memory is tight , Didreceivememorywarning was the only way to release useless memory before iphone OS 3.0, but the OS 3.0 and later the Viewdidunload method is a better way to set all Iboutlet (either property or instance variable) to nil in this method (System release When the view has been released) other view-related objects, other objects created at run time (but not system-required), objects created in viewdidload, cached data, and other release objects are freed from this method. Set the object to nil (Iboutlet only need to set it to nil, the system release view has already been removed) Viewdidunload is generally considered to be a viewdidload mirror, because when the view is re-requested, Viewdidload will also be re-executed viewdidunload the object in the release must be an object that is easily recreated (such as an object created in Viewdidload or another method). Do not release user data or other objects that are difficult to recreate Dealloc methods Viewdidunload and Dealloc methods are not associated, dealloc or continue doing what it should do  16. When was the didreceivememorywarning of Viewcontroller called? What is the default action? When the program receives a memory warning, the view controller will receive this message: Didreceivememorywarning starts from iOS3.0, does not need to overload this function, the memory freed generationto the Viewdidunload. The default implementation of this function is to check if the controller can safely release its view (here The bold view refers to the controller's view property). For example, view itself is not superview and can be easily reconstructed (from nib or Loadview function). If view can be released, then this function frees the view and calls Viewdidunload. You can overload this function to release other memory used in the controller. But remember to call the super implementation of this function to allow the parent class (typically Uiviewcontroller) to release the view. If your viewcontroller holds a reference to the view's child view, you should release these references in this function in the earlier versions of iOS. In iOS3.0 or later, you should release these references in Viewdidunload.  17. How do you understand MVC, and how is MVC implemented in cocoa? The MVC design pattern considers three types of objects: Model objects, view objects, and controller objects. Model objects represent special knowledge and expertise that are responsible for preserving the data of the application and the logic that defines the operational data. The View object knows how to display the model data for the application and may allow the user to edit it. The Controller object is the coordinator between the application's view object and the Model object. What is the difference between 18.KVC and KVO, and under what circumstances are they used? KVC (key-value-coding) KVO (key-value-observing) understand KVC and KVO (key-value-encode and key-value-monitor) when invoking an object via KVC, for example: [Self Valueforkey "Somekey"] , the program automatically attempts to parse the call in several different ways. First find whether the object with Somekey this method, if not found, will continue to find whether the object with Somekey this instance variable (iVar), if not found, the program will continue to attempt to invoke-(ID) Valueforundefinedkey: This method. If this method is not implemented, the program throws a Nsundefinedkeyexception exception error. (Key-value coding Find method, not only will find Somekey this method, but also find Getsomekey this method, preceded by a get, or _somekey and _getsomekey these forms. Also, finding instance variables will not only look for Somekey variables, but will also look for _somekeyWhether this variable exists. Design Valueforundefinedkey: The main purpose of the method is that when you use the-(ID) Valueforkey method to request a value from an object, the object can have a last chance to respond to the request before the error occurs. What does   19.id and nil represent? Idid and void * are not exactly the same. In the above code, the ID is a pointer to the struct objc_object, which basically means that the ID is a pointer to any object that inherits the class of object (or NSObject). It is important to note that the ID is a pointer, so you do not need to add an asterisk when using the ID. For example, ID foo=nil defines a nil pointer that points to an arbitrary subclass of NSObject. The ID *foo=nil defines a pointer to another pointer, pointing to a subclass of NSObject.  nilnil and C have the same null, as defined in objc/objc.h. Nil represents a Objctive-c object with a pointer to null (Nothing is empty).  20. Memory management autorelease, retain, copy, assign set method and meaning? 1, you Initialize (Alloc/init) The object, and you need to release it (release).  For example: Nsmutablearray aarray = [[Nsarray alloc] init];  After, need [Aarray release]; 2, you retain or copy the, you need to release it.  For example: [Aarray retain], need [Aarray release]; 3, the object that is passed (assign), you need to consider the retain and release.  For example: Obj2 = [[Obj1 somemethod] autorelease]; Object 2 receives an automatically freed value of object 1, or passes a base data type (nsinteger,nsstring): You or you want to retain object 2 to prevent it from being automatically freed before it is used. But after retain, be sure to release it at the right time.  21. Summary index COUNT (Reference counting) Retain value = Index count (Reference counting) Nsarray object retain (retain value plus one) object in any array. When Nsarray is unloaded (deallOC), all objects in the array are freed once (retain value minus one). Not only Nsarray, but any collection class (Collection Classes) performs a similar operation.  such as nsdictionary, or even uinavigationcontroller. Alloc/init the object that is created, the index count is 1.  No need to retain it again. Methods such as [Nsarray array] and [NSDate Date] Establish an object with an index count of 1, but it is also an automatic release object. So it's a local temporary object, so it doesn't matter.  If you are a variable (IVAR) that you intend to use in a full class, you must retain it. The default class method return value is executed with the "auto-release" method. (* Nsarray in the above) in the Unload method "Dealloc" in the class, release all the NS objects that are not balanced. (* All autorelease, while retain value is 1)  22. What is the role of the category? Sometimes we need to add some methods to a class that has already been defined, rather than rewriting the class. For example, when the project is already large, the amount of code is greater, or there are many methods already wrapped in the class, and other code has called the class to create the object and use the method of the class, you can use the class to extend the new method.   Note: Categories can only extend methods, not member variables. Delegate (for example) a delegate agent (Degegate), as the name implies, to delegate what an object does to other objects to do. Then the other object is the agent of this object, instead of it to take care of what to do. Reflected in the program, the first thing to know is the object of the client is which object, the delegate is what the content. Entrust mechanism is a design pattern, used in many languages, this is only a general idea, there will be a lot of information on the Internet. So in the Apple development process, with the implementation of the delegation of the idea of the program as follows, I mainly take how to transfer information between views to do an example. For example: in two pages (Uiiview view object) Implementation of the value, with the delegate (delegate) can do well! Method: Class A@interface a:uiview        ID transparendvaluedelegate;        @property ( Nomatic, retain) ID transparendvaluedelegate; @end   @implemtion a@synthesize Transparendvaluedelegate-(void) function{       nsstring* value = @ "Hello";     // Let the proxy object perform transparendvalue actions       [transparendvaluedelegate transparendvalue:value];} @end   class B@interface b:uiview      nsstring* value; @end   @implemtion B-(void) transparendvaluensstring*) fromvalue{      value = fromvalue;      NSLog (@ "The value is%@", value); &nbsp} @end  //The following setting a proxy delegate object is b//at defining a and Class B objects:  a* a = [[A alloc] init]; b* B = [[B alloc] init];a. transparendvaluedelegate = b;//Set Object A proxy As Object b  This allows the value to be passed through a delegate between views A and B!   The following example delegate has two types: 1, a View class object proxy object is the parent view, the child view with the proxy implementation let the parent view display other child View 2, a child view under the same parent view is another child view of the proxy object, Let another child view change its background color to the given color =============================================== the canonical format is as follows: @protocol transparendvaluedelegate;   @interface a:uiviewid< transparendvaluedelegate > m_dtransparendvaluedelegate; @property (nomatic, retain ) ID m_dtransparendvaluedelegate; Declaration of @end//proxy agreement @protocol transparendvaluedelegat{     -(void) transparendvaluensstring*) Fromvalue;}

Some common questions and answers in OC

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.