Write an implementation of the NSString class
+ (id)initWithCString:(c*****t char *)nullTerminatedCString encoding:(NSStringEncoding)encoding;
Copy the code
+ (id) stringWithCString: (c*****t char*)nullTerminatedCString
encoding: (NSStringEncoding)encoding
{
NSString *obj;
obj = [self allocWithZone: NSDefaultMallocZone()];
obj = [obj initWithCString: nullTerminatedCString encoding: encoding];
return AUTORELEASE(obj);
}
Copy the code
###static
- The static variable is used in the function body. Unlike the auto variable, the memory of the static variable is allocated only once. Therefore, the value of the static variable remains the same in the next call.
- Static global variables in a module can be accessed by functions inside the module, but not by other functions outside the module.
- A static function in a module can only be called by other functions in the module. The use of this function is restricted to the module in which it was declared.
- A static member variable in a class is owned by the entire class. There is only one copy of all objects in the class.
- The static member function in a class is owned by the whole class. This function does not receive the this pointer, so it can only access the static member variable of the class.
### The difference between thread and process
- Process and thread are the basic unit of the program run by the operating system. The system uses the basic unit to realize the system’s concurrency to the application.
- The main difference between procedures and threads is that they are different ways of managing operating system resources. Processes have independent address Spaces, a crash of one process in protected mode does not affect other processes, and threads are just different execution paths within a process. Thread has its own stack and local variables, but there is no separate address space between threads, a thread dead is equal to the whole process dead, so multi-process procedures than multithreaded procedures robust, but in the process switch, the cost of resources is larger, the efficiency is poor. However, for concurrent operations that require simultaneous and variable sharing, only threads, not processes, can be used.
### The difference between heap and stack
#### management: for the stack, it is automatically managed by the compiler, without our manual control; In the case of the heap, the release is controlled by the programmer, leading to memory leaks. #### Request size: stack: Under Windows, a stack is a data structure that extends to a lower address and is a contiguous area of memory. The address at the top of the stack and the maximum size of the stack are specified by the system. Under WINDOWS, the stack size is 2M (or 1M). If the stack size exceeds the available space, overflow will be prompted. Therefore, less space can be obtained from the stack. 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 uses a linked list to store the free memory address, which is naturally discontinuous, and the traversal direction of the list is from low address to high address. The size of the heap is limited by the amount of virtual memory available in the computer system. Thus, the heap is more flexible and larger. #### fragmentation problem: For the heap, frequent new/ DELETE is bound to cause memory space discontinuity, resulting in a large amount of fragmentation, making the program inefficient. For stacks, this is not a problem because stacks are first-in, last-out queues, and they are so one-to-one that there can never be a block of memory ejected from the middle of the stack #### allocation: the heap is allocated dynamically, there is no statically allocated heap. There are two types of stack allocation: static allocation and dynamic allocation. Static assignment is done by the compiler, such as assignment of local variables. Dynamic allocation is done by the Alloca function, but stack dynamic allocation is different from heap dynamic allocation, which is released by the compiler without manual implementation. #### allocation efficiency: the stack is a data structure provided by the machine system, and the computer provides support for the stack at the bottom: special registers are allocated to store the address of the stack, and special instructions are executed to push and unload the stack, which determines the high efficiency of the stack. The heap is provided by the C/C++ library, and its mechanism is quite complex.
### what is key-value and what is key-path
The nature of the model is specified by a simple key (usually a string). Views and controllers use keys to find the corresponding property value. In a given entity, all values of the same attribute have the same data type. Key-value coding is used for such lookups – it is a mechanism for indirectly accessing object properties. A key path is a string of dot-delimited keys used to specify a concatenated sequence of object properties. The properties of the first key are determined by the preceding properties, and the values of each subsequent key are also relative to the preceding properties. Key paths allow you to specify the properties of related objects in a way that is independent of the model implementation. With key paths, you can specify a path in an object graph at any depth to point to a specific property of the object in question.
### Target-action mechanics
The target is the receiver of the action message. A control, or more commonly its units, holds the destination of its action messages in the form of socket variables (see section “socket variables”). An action is a message that the control sends to the target or, from the target’s perspective, a method that the target implements in response to the action. Programs need some mechanism to translate events and instructions. This mechanism is the goal-action mechanism.
### objC memory management
- If you create an object by allocating and initializing ** (such as [[MyClass Alloc] init]) **, you own the object and are responsible for releasing it. This rule also applies when using NSObject’s convenience method new.
- If you copy an object, you own the copied object and are responsible for releasing it.
- If you keep an object, you partly own it and need to release it when it is no longer in use.
- If you receive an object from another object, you do not own it and should not release it (there are a few exceptions to this rule, which are explicitly stated in the reference documentation).
What is an automatic release pool and how does it work
- When you send an AutoRelease message to an object, Cocoa puts a reference to that object into the latest automatic release pool. It is still a valid object, so other objects in the scope defined by the autorelease pool can send messages to it. When the program executes at the end of the scope, the auto-release pool is released, and all objects in the pool are released.
- Ojc-c has its own “reference counting” system, which contains its own memory. The object allocates its own memory to a single reference and contains a copy of its own memory. The reference count is reduced by one whenever release and autoRelease are encountered, and if the object’s count becomes zero, it is destroyed by the system.
- NSAutoreleasePool is used to manage reference counts, which you don’t usually have to do.
- There is no difference between an autorelease and a release, except that when the reference count is decrement by one, an autorelease does the decrement by one when the object’s use is actually over.
What is the class factory method
Class factory methods are implemented to provide convenience to customers by combining allocation and initialization in one step, returning the created object, and automatically releasing it. These methods are of the form +(type)className… (where className does not include any prefix) the factory method may be more than just a convenience. They not only combine allocation and initialization, but also provide assignment information for the initialization process. Another purpose of the class factory approach is to enable classes (such as NSWorkspace) to provide singleton instances. Although the init… Method can confirm that only one instance of a class exists each time the program runs, but it first needs to allocate a “live” instance, and then it must be freed. The factory approach avoids blindly allocating memory for objects that may not be useful.
What is a singleton instance
Some classes in the Foundation and Application Kit frameworks only allow the creation of singleton objects, which are unique instances of those classes in the current process. For example, the NSFileManager and NSWorkspace classes are used to instantiate singleton objects on a process-based basis. When an instance is requested from these classes, they pass you a reference to a single instance, which is allocated and initialized first if it doesn’t already exist. Singleton acts as a control center, directing or coordinating the various services of the class. If the class is conceptually only one instance (such as NSWorkspace), a singleton instance should be generated, rather than multiple instances; If you might someday have multiple instances, you can use the singleton mechanism instead of factory methods or functions.
## dynamic binding
#### determines the method to invoke at run time. Dynamic binding also postpones the determination of invoked methods until runtime. At compile time, method calls are not tied to the code, and the code being called is identified only after cancellation is sent. With dynamic typing and dynamic binding techniques, your code can get different results each time it is executed. The runtime factor is responsible for determining the receiver of the message and the method being invoked. The message distribution mechanism at runtime provides support for dynamic binding. When you send a message to an object whose type is dynamically determined, the runtime system locates the object’s class through the recipient’s ISA pointer and determines the method to be invoked from there. The method and message are dynamically bound. Moreover, you don’t have to do anything in objective-C code to automatically reap the benefits of dynamic binding. Every time you send a message. In particular, dynamic binding occurs routinely and transparently when the receiver of the message is an object whose dynamic type has been determined.
### the pros and cons of obJ-C
# # # # objc advantages:
- Cateogies
- Posing
- Dynamic identification
- Index calculation
- Elastic messaging
- Not an overly complex C derivative language
- Objective-c and C++ can be mixed programming
# # # # objc faults:
- Namespaces are not supported
- Operator overloading is not supported
- Multiple inheritance is not supported
- With dynamic runtime types, all methods are function calls, so many compile-time optimization methods are not used. (such as inline functions), poor performance.
###sprintf,strcpy,memcpy
- strcpyIs a string copy function whose function prototype is
strcpy(char *dst, const char *src);
Copy a string that starts with SRC into the memory that starts with DST and ends with ‘\0’. Since the length of the copy is not controlled by ourselves, this string copy is prone to error.- Functions that copy strings arememcpy, this is a memory copy function, its function prototype is
memcpy(char *dst, const char* src, unsigned int len)
; Copy len of memory from SRC to DST. This function has a controllable length. But there is the problem of memory overlay.- Sprintf is a formatting function. To format a piece of data into a string buffer in a specific format. The length of the sprintf formatting function is not controllable. It is possible that the formatted string will exceed the size of the buffer, causing an overflow.
### What the hell are these
- int a; // An integer
- int *a; // A pointer to an integer
- int **a; // A pointer to a pointer to an integer
- int a[10]; // An array of 10 integers
- int *a[10]; // An array of 10 pointers to integers
- int (*a)[10]; // A pointer to an array of 10 integers
- int (*a)(int); // A pointer to a function a that takes an integer argument and returns an integer
- int (*a[10])(int); // An array of 10 pointers to function that take an integer argument and return an integer
### Readwrite, readonly, assign, retain, copy, nonatomic attributes
@property is a property access declaration that supports the following attributes:
- Getter =getterName, setter=setterName, sets setter and getter method names
- Readwrite,readonly, sets the level of access available
- The assign method does not perform any retain operations to solve the problem of primitive type and loop reference
- Retain, setter methods release the old values and retain the new values, all implementations in this order (see CC)
- Copy, setter method copy, same as retain process, old value release, copy new object, retainCount is 1. This is a mechanism introduced to reduce dependency on context. Copy is used when you don’t want a and B to share a piece of memory. A and B each have their own memory.
- Nonatomic, non-atomic access, no synchronization, multi-threaded concurrent access improves performance. Note that without this attribute, both access methods are atomic transaction access by default. The lock is added to the instance level of the owning object. .
- Atomic and nonatomic are used to determine whether getters and setters generated by the compiler are atomic operations. In a multithreaded environment, atomic manipulation is necessary, otherwise error results may be caused.
When to use delegate and when to use Notification?
Delegate for one-to-one relationships, and Reciever can return values to the sender. Notification can return values for one-to-one/many/ None, and Reciever cannot return values to the sender. So, the delegate is used for the sender that wants to receive a function from reciever, and the notification is used to notify multiple Objects of an event.
### What are KVC and KVO?
####KVC(Key-Value-Coding)
Key-value encoding is a mechanism for indirectly accessing properties of an object using a string to identify the properties, rather than calling access methods, directly or through instance variables. In many cases, you can simplify your program code. The Apple documentation actually gives a good example.
Internal implementation: when an object is called setValue,
- The first step is to find the environment parameters needed to run the method based on the method name.
- He will find the interface that the specific method implements from his OWN ISA pointer combined with the environment parameters.
- Then directly find the specific method to achieve.
####KVO (key-value-observing) : a key-value Observing mechanism, which provides methods for Observing the changes of a certain attribute, greatly simplifying code. One of the things that we used to see is the monitoring of the status of button clicks.
When an observer registers an object’s property and the observed object’s ISA pointer is modified, the ISA pointer points to an intermediate class instead of the real class. So the ISA pointer does not need to point to the actual class of the instance object. So it’s best for our program not to rely on isa Pointers. When calling a class method, it is best to specify the class name of the object instance
Let’s say I made a button
[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 isEqualToString:@"highlighted"] ) {
[self setNeedsDisplay]; }}Copy the code
For the system, the value can be changed according to keypath, which is theoretically the same as the KVC mechanism. #### on how the KVC mechanism finds value through key: “When an object is called through KVC, such as: [self valueForKey:@” someKey “], the program automatically tries to resolve the call in several different ways. If not, we will continue to look for an instance variable (iVar) with someKey. If not, we will continue to try to call -(id) valueForUndefinedKey:. If the method is still not implemented, the program throws an NSUndefinedKeyException exception. Note: key-value Coding does not only find someKey, but also getsomeKey, with get or _someKey or _getsomeKey. (someKey = ‘someKey’) (_someKey = ‘someKey’) The main purpose of the valueForUndefinedKey: method is that when you use the -(id)valueForKey method to request a value from an object, the object has a last chance to respond to the request before an error occurs. There are many benefits to doing this, and the following two examples illustrate the benefits. ‘There’s something to be said for coming from Cocoa. Because we know button is a highlighted instance variable. So why do we just add an associated keypath above
When is loadView, viewDidLoad, viewDidUnload called? What do you do in these functions when you’re customizing a ViewController?
ViewDidLoad is called when the view is initialized from the NIB file loadView is called when the view of the controller is nil. This method is called when implementing the view programmatically. The View controller registers memory warning Notification by default. ViewDidUnload is called when any view of the View controller is not used. This is where you implement the view release of the retain, if it’s the IBOutlet view property of the retain you don’t release it here,IBOutlet will release it.
### Process oriented vs. Object oriented
#### process oriented is to analyze the steps needed to solve the problem, and then use the function to achieve these steps step by step, when using one by one can be called. #### Object orientation is to decompose the transaction that constitutes the problem into various objects. The purpose of establishing objects is not to complete a step, but to describe the behavior of something in the whole step of solving the problem.
### The role of categories
- Spread the implementation of a class across multiple different files or frameworks.
- Create a forward reference to a private method.
- Add an informal protocol to an object.
### Category limitations
- New instance variables cannot be added to the class because the class has no place for instance variables.
- Name conflict, which means that when a method in a category conflicts with the original class method name, the category takes higher precedence. The class method completely replaces the initial method and can no longer be used. The limitation of not being able to add instance variables can be solved using dictionary objects.
What does the ### keyword volatile mean? And give three different examples
A variable defined as volatile means that it can be changed unexpectedly, so that the compiler does not make assumptions about its value. To be precise, the optimizer must carefully re-read the value of the variable each time it is used, rather than using a backup stored in a register. Here are some examples of volatile variables:
- Hardware registers of parallel devices (e.g., status registers)
- Non-automatic variables that will be accessed in an interrupt service subroutine
- A variable shared by several tasks in a multithreaded application
Can a parameter be both const and volatile? Explain why.
Yes. One example is a read-only status register. It is volatile because it can be changed unexpectedly. It’s const because the program shouldn’t try to modify it.
Can a pointer be volatile? Explain why.
Yes. Although it’s not very common. An example is when a service subroutine fixes a pointer to a buffer.
# # # @ synthesize and @ dynamic
At sign synthesize is the system automatically generating getter and setter property declarations. Unless the developer has already done so, the compiler generates the code to satisfy the property declaration.
@dynamic is the property declaration provided by the developer. You need to provide setters for read-only properties and setters and getters for read-write properties. Is to tell the compiler that the methods of obtaining and assigning attributes are implemented by the user and not automatically generated.
###Difference between shallow copy and deep copy? (What’s the difference between shallow copy and deep copy?)
#### Shallow copy: Copies only Pointers to objects, not reference objects themselves. #### Deep copy: Copies the reference object itself.
It means that I have A object, get A_copy object after A copy, for shallow copy A and A_copy point to the same memory resources, copy of just is A pointer, the object itself is only A resources, that if we are to modify A_copy performed operation, then find A reference object is modified, This actually violates one of our ideas about copying. Deep copy is easy to understand. There are two separate objects in memory.
In the colloquial words of a friend on the Internet:
Shallow copy is like you and your shadow, you die, your shadow dies deep copy is like you and your clone, you die, your clone lives.
###What is advantage of categories? (What do categories do?) ###What is difference between implementing a category and inheritance? (What is the difference between inheritance and category implementation?)
You can add new methods to a category without knowing or changing the original code. You can only add, not delete. And if there is a name conflict between a category and a method in the original class, the category overrides the original method because the category has higher precedence.
Categories have three main functions:
- Spread the implementation of a class across multiple different files or frameworks.
- Create a forward reference to a private method.
- Add an informal protocol to an object.
Inheritance can add, modify, or delete methods, and can add attributes.
###Difference between categories and extensions? (The difference between categories and class extensions)
The difference between categories and extensions is that the latter can add attributes. In addition, the latter method must be implemented. Extensions can be thought of as a private Category.
###Difference between protocol in objective c and interfaces in java? (What is the difference between the protocol concept in OC and the interface concept in Java?)
The agent in OC has two meanings, formally defined as formal and informal protocol. The former is the same as a Java interface. The methods in the informal Protocol belong to the design pattern consideration and are not required to be implemented, but if implemented, it will change the class properties. I actually looked at formal agreements, categories and informal agreements a long time ago, and I wrote about them in the tutorial. “Informal agreements are just another way of saying categories.” Here are some ways you might want to implement them, so you can use them to get the job done.” That means these are optional. For example, if we want a better method, we will declare such a class to implement. Then you can use these better methods directly at a later stage. In this way, it always feels like the category thing is sort of an alternative protocol to a protocol.” For now, protocal has already started to standardize on both, because the source says “informal protocols use interface qualifiers”, and now we see two qualifiers in the protocol: “Mandatory (@requied)” and “optional”.
###What is purpose of delegates? (The role of agency?)
The purpose of an agent is to change or transfer the chain of control. Allows a class to notify other classes at certain times without having to retrieve Pointers to those classes. You can reduce framework complexity. On another point, proxies can be understood as an analogy to the callback listening mechanism in Java.
###What are mutable and immutable types in Objective C? (Types that can and cannot be modified in OC)
A collection class that can be modified but cannot be modified. This is my personal simple understanding is dynamic add modification and not dynamic add modification. Like NSArray and NSMutableArray. The former memory control after initialization is fixed immutable, the latter can be added, etc., can dynamically apply for new memory space.
###When we call objective c is runtime language what does it mean? (What do we mean by oc being the Runtime language?)
Polymorphism. Basically, the determination of data types is deferred from compile time to run time. This question really involves two concepts, run-time and polymorphism. In simple terms, the runtime mechanism allows us to not determine the class of an object and call the method specified by that class object until runtime. Polymorphism: The ability of different objects to respond to the same message in their own way is called polymorphism. It is assumed that all life classes use the same method — eat; Then, human beings and pigs are also creatures. After inheriting life, they both realize 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 (in response to the eat selector). Thus it can be said that the runtime mechanism is the foundation of polymorphism.
###what is difference between NSNotification and protocol? (What’s the difference between a notice and an agreement?)
The protocol has a chain of control (HAS-A) relationship; the notification does not.
First of all, I didn’t quite understand what the chain of control was at first. But a brief analysis of the behavior patterns of notifications and agents can give us a rough idea.
In simple terms, notifications can be one-to-many, and a message can be sent to multiple message recipients. Acting according to our understanding, not to say directly can not be many, for example we know the star economic agent, a lot of times an economic person is responsible for several star affairs. Just for different stars, the objects of the agency are not the same, one by one correspondence, it is impossible to say that tomorrow to deal with A star to A press conference, the agent issued the news of the processing of the press conference, called B’s press conference. But notifications are different. They only care about sending notifications, not how many are received and interested in processing them. So chain of control (HAS-A), as you can roughly see from the English word, the correspondence between single ownership and controllable.
###What is push notification? (What is push notification?)
Push notifications are more of a technology. It is simply a way for the client to obtain resources. In most cases, the client takes the initiative to pull. Push is an active server-side push.
# # # Polymorphism? (On polymorphism)
Polymorphic, subclass Pointers can be assigned to the parent class.