iOS face questions

Source: Internet
Author: User
Tags variable scope

How much does object-c inherit? What's the substitute for nothing?

All classes in cocoa are subclasses of NSObject
Multi-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.


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, as the OO principle is that an object exposes only useful things. Without a private method, it would be less convenient 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 variables
In Objective‐c, all instance variables are private by default, and all instance methods are public by default

Keyword const what meaning

Const means "read-only," what does the following declaration mean?
const int A;
int const A;
const int *a;
int * const A;
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 modifiable, but the pointer can). The fourth meaning a is a constant pointer to an integer number (that is, the integer number pointed to by the pointer can be modified, but the pointer is non-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 function of the keyword const is to convey very useful information to the person who is reading your code, and in fact, declaring a parameter as a constant is to tell the user the purpose of the parameter's application. If
You'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 clear
Management. )
•; By giving some additional information to the optimizer, using the keyword const may produce more compact code.
•; Proper 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 initially
Start, 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 both
Fixed 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".

What does 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 the
This 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.

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 declaration
within 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.

#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 #import
And #import's advantage over # include is that it doesn't cause duplicate inclusions

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.

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 popped
Allocation 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.

Object-c memory management?

1. When you create an object using the New,alloc and copy methods, the object has a retention counter value of 1. When you no longer use the object, you are responsible for sending a release or Autorelease message to the object. This way, the object will be destroyed 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.

Why are the properties of many built-in classes, such as Tableviewcontroller delegate, assign not retain?

Circular references
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.
• Object C was 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.

When defining attributes, what is the use of copy, assign, retain?

Assign for simple data types, such as Nsinteger,double,bool,
Retain and copy are used for objects,
Copy is used when a to point to an object, B also want to point to the same object, if you use Assign,a if released, then call B will crash, if 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];
property = [NewValue retain];
}

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 autoreleasepool so that all releasepool will form a stack like callstack, and 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, a Timer call, a delegate call, will be a new runloop

Does iOS have 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 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 Tableviewdequeuereusablecellwithidentifier: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 scenario at which the program initially shows TableView is:

1. Create 10 cells with [[UITableViewCell Alloc]initwithstyle:uitableviewcellstyledefault Reuseidentifier:cellidentifier], and assign 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 the TableView down, 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 Viewcontroller's Loadview, Viewdidload, and Viewdidunload called, and what should be done in these functions when customizing Viewcointroller?

From the relationship of Init, Loadview, Viewdidload, Viewdidunload, Dealloc
Init method
Instantiate the necessary objects in the Init method (follow the lazyload idea)
Initialize the Viewcontroller itself in the Init method

Loadview method
Viewcontroller calls this method when the view needs to be displayed and it is nil. Do not call the method directly.
If you manually maintain views, you must override this method by overloading
If you use IB to maintain views, you must not override this method with overloading

Loadview and IB Build view
You implement the Loadview method in the controller, then you may be called by the memory management control at some point when the application is running. If the device is low on memory, the view controller receives a didreceivememorywarning 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.

Viewdidload method
Viewdidload This method is called only when view is initialized from the nib file.
Overloads override this method to further customize the view
In the iphone OS3.0 and later versions, you should also overload the rewrite Viewdidunload to release any indexes on the view
Call data Model after Viewdidload

Viewdidunload method
This method is called when the system memory is tight (note: Viewcontroller is not dealloc)
When memory is tight, didreceivememorywarning is the only way to release useless memory before iphone OS3.0, but OS 3.0 and later Viewdidunload methods are a better way
In this method, all Iboutlet (either property or instance variables) are set to nil (the System release view has already been removed)

When you release other view-related objects in this method, other objects created at run time (but not system-required), objects created in viewdidload, cached data, and other release objects, the object is set to nil (Iboutlet only need to be set to nil. System release view has been removed)

It is generally assumed that viewdidunload is a viewdidload mirror, because Viewdidload is also re-executed when view is re-requested

The Viewdidunload object must be an object that is easily recreated (such as an object created in Viewdidload or other methods), and do not release user data or other objects that are difficult to re-create

Dealloc method
Viewdidunload and Dealloc methods are not associated, dealloc still do what it's supposed to do


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

Starting with iOS3.0, you do not need to overload this function to put the freed memory code into 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), such as the view itself is not superview and can be easily reconstructed (from nib or Loadview functions).

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.

Enumerating the common multi-threaded implementations in cocoa, and talking about several ways to solve multi-thread security, what kind of multithreading can be used in general?

Nsoperationnsthread
@sychonized

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.
Viewcotroller
Xib

What is the difference between delegate and notification, and how are they used in each case?

KVC (key-value-coding)
KVO (key-value-observing)
Understanding KVC and KVO (key-value-encoding and key-value-monitoring)

When invoking an object through KVC, such as: [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. At the same time, finding the instance variable will not only look for the variable somekey, but also find out if the _somekey 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.


Self. What's the difference between self and self?


What does ID and nil mean?

Id

The ID 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.

Nil

Nil is the same as NULL in the C language, as defined in objc/objc.h. Nil represents a Objctive-c object with a pointer to null (Nothing is empty).

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 the need

[Aarray release];

2, you retain or copy the, you need to release it. For example:

[Aarray retain]

After the 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.

Questions about index count (Reference counting)

Retain value = Index count (referencecounting)

The Nsarray object retain the object in any array (retain value plus one). When Nsarray is unloaded (Dealloc), all objects in the array are freed once (the retain value is reduced by one). Not only Nsarray, but any collection class (Collectionclasses) 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 not autorelease, while retain value is 1)

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)

The principal agent (Degegate), as the name implies, entrusts something 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) idtransparendvaluedelegate;
@end

@implemtion A
@synthesize transparendvaluedelegate
-(void) Function
{
nsstring* value = @ "Hello";
Let proxy object perform Transparendvalue action
[Transparendvaluedelegate Transparendvalue:value];
}
@end

Class B
@interface B:uiview
nsstring* value;
@end

@implemtion B
-(void) Transparendvalue: (nsstring*) Fromvalue
{
value = Fromvalue;
NSLog (@ "The value is%@", value);
}
@end

The following settings a proxy delegate object is b
At defining A and Class B objects:

* a = [[a alloc] init];
b* B = [[B alloc] init];
A. transparendvaluedelegate = b;//Set Object A proxy is object B

This allows the values to be passed between views A and B through a delegate!

The following example delegate has two categories:
1. The proxy object for a view class object is the parent view, and the child view uses the proxy implementation to have the parent view display a different child view
2. One child view under the same parent view is a proxy object for another child view, so that another child view changes its background color to the given color
===============================================
The canonical format is as follows:
@protocol transparendvaluedelegate;

@interface A:uiview
id< transparendvaluedelegate > m_dtransparendvaluedelegate;
@property (nomatic, retain) ID m_dtransparendvaluedelegate;
@end
Statement of the Proxy agreement
@protocol transparendvaluedelegat<nsobject>
{
-(void) Transparendvalue: (nsstring*) Fromvalue;
}

Retaincount?

iOS face questions

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.