Objective-C Analysis

Source: Internet
Author: User

Objective-C Analysis
1. Introduction I have been engaged in IOS development since today, and then PHP development to better understand development. Objective-C is the prerequisite for IOS development. This article briefly summarizes its knowledge points.
What is Objective-C? It is an object-oriented extension of C.
2. Knowledge Point 1. Objective-C class definition has two parts: Interface part and implementation part. Interface section:
@ Interface className: superclassName
{
Instance variable declarations
}
Method declarations
@ End

Implementation part: Implementation of class methods.
2. NSObject has a unique root class. Almost all Objective-C classes are directly or indirectly subclasses of NSObject. It defines the class factory method alloc, allocates memory for object instances and instance methods that require interaction with the Objective-C memory management system.
3. Message Objective-C uses a different method called message.

[receiver message]
Aggreger executes the object of a method.
Message method name
In any case, the code in square brackets means that you are sending a message (a method call) to an object or a type ).
4. The word starting with '@' in a compiler instruction is a compiler instruction rather than code execution.
5. The key word id stores the type of pointer to the object (the id type means that the variable myObject can be any type of object. Therefore, when you compile this code, the actual type of the Code and the method compiler it implements are unknown.) in Objective-C, all object variables are pointer types. The id type has been predefined as the pointer type, so you do not need to add an asterisk.
Nil is a defined constant pointing to no object pointer.
The nil message indicates no operation: They do nothing and continue to execute the next line of code.

In Objective-C, nil Objects Act as NULL pointers in many other languages. The difference is that calling methods on nil does not cause program crashes or throws exceptions. We do not need to check whether the object is empty before calling the method of an object. If you call a nil object method and the method returns a value, you will get a nil return value.

BOOL, YES, NO Boolean
The abbreviation of SEL selector, selector, which stores a type represented by an Objective-C method name.
Imp a typedef, used to 'a pointer that points to the function that receives the parameter id, sel, and other possible parameters and returns the id'
Class stores a Class reference.
6. Cocoa numeric type NSInteger
NSUInteger
CGFloat
NSLog
7. Development file. l UNIX man page file
. M program source file
. Pch pre-compiled header file
. H program header file
8. Message forwarding NSInvocation is an Objective-C message expression encapsulated as an object. It defines the parameter methods for setting and obtaining the receiver, selector, and encapsulated message expressions, and obtaining the return value.
9. Various attributes of objects can be found during runtime in the internal province runtime. This process is called the internal province.
10. @ class executes a class type.
11. copy of copyNSObject to copy objects.
Light copy, deep value assignment, variable copy (NSArray, NSDictionary, NSSet), and variable value assignment (NSNumber, NSColor ).
12. When memory management allocates memory on the heap, it is no longer needed to be released.
Malloc-"free
13. Message Details 1. nesting
Any message parameter can be replaced by a message expression of the corresponding type.

The key to message transmission is the data structure used by the compiler to build each class and object.
Each class contains the following two elements:
-A pointer to the parent class.
-A scheduling table ).
This scheduling table associates the selector of the class with the actual memory address of the method.
Each object has a pointer to its class isa. Through this pointer, the object can find the class to which it belongs, and all its parent classes are also found.

2. send messages to nil
Sending a message to an nil receiver has no effect.

3. Send messages to self
The method of an object calls another method of the same object. The variable self must be used as the message recipient.

4. Overwrite and send messages to super
Classes can provide a different implementation in their @ implementation section to overwrite the methods defined in their superclasses.
14. selector compiler instruction @ selector () converts a method name to a SEL
The method name of a message is sometimes called a selector or method selector, because it is used at runtime to select the receiver method to be executed.
15. When the efficiency compiler converts your method to a C function, it adds the self and _ cmd parameters before the parameter list. When calling a function through its IMP, fill in these parameters. Direct function calls are several times faster.
16. A variable of class type, used as a pointer to a class object. You can call the class method using the class name as the receiver to obtain a pointer to the class object.
17. A single shared instance class. A single class is usually used to wrap operating system services or to detect UI items such as a panel.
18. The Framework framework is a type of package that dynamically loads shared resources. The generic name is in the format of frameworkName. framework.
1. Objective-C or C framework
2. Cocoa framework
Apple indicates the name of a mac program written using Objective-C technology. It is an umbrella framework, including three main frameworks (Foundation, Appkit, and Core Data );
3. AppKit framework
Class required for building GUI applications
4. Core Foundation
A low-level C language framework. An object has a memory management system for reference counting. objects with the same memory layout can be freely converted.
5. Core Graphics
A low-level API for Quartz 2D graphics.
6. Core Animation
Animation Frame
7. WebKit
8. ImageIO
9. Core Image
10. Core Audio
11. OpenGL
12. OpenAL
19. The basic classes of variable classes and immutable classes are immutable, but there are variable and immutable classes used for characters or bytes.
20. classless clustering hides complexity behind a simple interface. A publicly visible class is an abstract class.
Class: NSString, NSArray, NSDictionary, NSSet, NSNumber, and NSData are all class clusters.
21. An array of bytes of the NSString and NSMutableString characters followed by a NULL byte.
If we call methods that are not supported by NSString objects, the compiler will issue a warning.
C string can be exchanged with NSString
NSMutableString is a variable subclass.
22. Collection classes NSArray, NSDictionary, NSSet, and their variable subclasses are all collection classes.
23. NSArrayC array, borderless check
24. NSDictionary provides a way to process key-value pairs.
25. NSSet object set implements a mathematical set
26. NSNumber stores and returns all the numeric types you like
27. NSNull has no object
28. NSData byte data, processing files or images, etc.
29. NSURLurl is used to specify the direction of file resources and network resources.
30. Use makeObjectsPerformSelectior of NSArray to create an implicit Loop
31. NSEnumerator receives the objects in the set and passes them out. Each time, it uses the nextObject method to return nil after sending.
32. abnormal conditions for the program to continue execution. Use the compiler instructions @ try, @ catch, and @ finally for processing
33. classification allows us to add methods to an existing class without subclass and without the source code of the classification class.
34. Extended extension allows you to declare a method outside the public field of view by adding an Interface part to the class declaration file. Provides an internal setter method to access the public and read-only instance variables you want.
35. @ property statement
@property(attributes)type name;
Attributes describes how to write accessors.
#import 
 
#import    
   
@interface Photo : NSObject {   
    NSString* caption;   
    NSString* photographer;   
}   
@property (retain) NSString* caption;   
@property (retain) NSString* photographer;   
   
@end

Category
#import    
               
@interface NSString (Utilities)   
- (BOOL) isURL;   
@end
36. assign, retain, and copy attributes affect the construction of the merging setter.
37. readwrite and readonly
38. nonatomic features declared as nonatomic are all atomic by default. If nonatomic is specified, the compiler merges the accessors without considering thread security.
? readwrite (default) or readonly: set the property to be read-write (with getter / setter) or read-only (only getter);
      ? assign (default), retain or copy: set how the property is stored;
      nonatomic: does not generate thread-safe code, it is generated by default (without the atomic keyword);
      ? getter = ..., setter = ...: change the default name of the accessor
39. Protocol protocols are a set of predefined methods. A class can be used to implement them.
Protocol-the protocol is used to follow the protocol, and the implementation method required by the protocol must be implemented.
Delegate-delegation, as its name implies, is to entrust others to handle affairs, that is, when one thing happens, it will not be handled by others.


When A view contains B view B view B view, you need to modify the view Interface.
Several steps are required
1. First, define a protocol.
2. Methods of a view Implementation Protocol
3. B view sets a delegate variable
4. Set the delegate variable of B view to a view, which means B view delegates a view to do things.
5. After an event occurs, use the delegate variable to call the Protocol method in a view.
Most of the time, you need to perform some operations on Class A in Class B. In this case, you need A proxy for Class B to complete, this is common and practical in applications.

About the Formal Agreement:


 .  @protocol protocolName    
. @optional -(void)delegateMethodA    
. @required -(void)delegateMethodB   
 . // other methods    . ...    
. @end  


Formal protocols are similar to java excuses or abstract classes.
The @ optional method can be implemented or not, but the @ required method must be implemented. The default value is @ required.
The delegate proxy is to set an instance variable of id type inside object a, and then assign another object B to this instance variable of object, in this way, you can call the method of object B by operating the id variable of instance variable.

To use a protocol class, you must implement the required methods of the protocol. You can freely implement or do not implement any optional methods of the Protocol.
The @ required command declares that the method is required.
40. TablePrinter provides a table printing Task Service for other objects.
Any sex-related TablePrinterDataSource protocol prints a table
41. The reference count Memory Management provides two alternative systems: reference count and automatic garbage collection.
Principle: each object stores a count, which is the number of other objects that use this object.
1, alloc, allocWithZone, new (with initialization)
Allocate memory for the object, retainCount is "1", and return this instance
2, release
The dealloc method of this object is called when retainCount minus "1" and is reduced to "0"
3, retain
RetainCount plus "1"
4, copy, mutableCopy
Copy an instance. If the number of retainCount is "1", this instance is returned. The obtained object is independent of other contexts (Clean object ).
5, autorelease
Add this object to the AutoreleasePool instance at the top of the autoreleasePool stack in the current context. Because of its introduction, Objective-C (non-GC management environment) is managed by full manual memory

To semi-automation. AutoreleasePool makes Objective-C a semi-automated language for memory management.
It is safer to use the autorelease method in the configurator, because the new and old values of the variables to be changed may point to the same object. But you may not want to immediately release the objects you actually want to keep.
42. You have created an object and you own it.
By sending a retain message to an object created by another person, you have it.
When you are finished, you must send a release message to release the ownership.
When it is no longer in use, it must be destroyed.
43. Garbage collection uses a running program to find objects that are no longer in use, destroy them, and return their bytes to the heap .).
There are actually two methods to release an object reference: release and autorelease. Standard release immediately releases object references. Autorelease will not be released after a while, but the reference will actually exist until the current method ends (unless you add custom code to change it explicitly ).
The dealloc method is called when an object is deleted from the memory. Usually, instance variables in all objects are released in this method.
The assigned (alloc) object, or objects that are retained in some places, must send a release message to them.
44. Strong references and weak references under the reference count, an object creates a strong reference to it by retaining another object, which ensures that the retained object remains active, until the object is retained
Use it and release it. On the contrary, an object creates a weak reference to another object by retaining the pointer of another object without retaining the object itself.
45. XCode, Objective-C, and CocoaXCode: You can regard it as a development environment, just like Visual Studio, Netbeans, or SharpDevelop. You can think of Interface Builder as a separate program that is used to draw interfaces in Visual Studio.
Objective-C: This is a language, as if c ++ is a language, Java is a language, c # is a language, and the history of Yingge is also a language.
Cocoa: There are a lot of function libraries, such as MFC,. NET, and Swing. People have already written a bunch of ready-made stuff. You only need to know how to use it.
46. # import, @ interface # import
You can think of it as # include. But it is best to use # import. Remember this.
# The import command automatically prevents the same file from being imported multiple times.
@ Interface commands
Interfaces of classes are usually stored in files similar to ClassName. h, defining the instance variables (protected) and public methods.
Class implementation is stored in files such as ClassName. m, which contains the actual implementation code of these methods. It also defines private object variables and methods that the customer class cannot access.
47. method call method of the called object:
output = [object methodWithOutput];   output = [object methodWithInputAndOutput:input];  
Method of calling class: (create object)
Id myObject = [NSString string]; or NSString * myString = [NSString string];
Nested call:
[NSString stringWithFormat:[prefs format]];  
Multiple Input parameters:
statement:
-(BOOL) writeToFile: (NSString *) path atomically: (BOOL) useAuxiliaryFile;
transfer:
BOOL result = [myData writeToFile: @ "/ tmp / log.txt" atomically: NO]; 
48. The Access Point syntax can only be used on setter and getter, but cannot be used in common methods.
setter
[photo setCation:@”Day at the Beach”];  
output = [photo caption];  
Point Operator
photo.caption = @”Day at the Beach”;   output = photo.caption;   
Only when the accesser does not exist will @ synthesize automatically generate the accesser. Therefore, even if @ synthesize is used to declare an attribute, you can still implement custom getter and setter. The compiler will only automatically generate methods that you do not have a custom method.
49. Create an object and create an object automatically released
NSString* myString = [NSString string];  
Manually create alloc
NSString* myString = [[NSString alloc] init];   
Note: [NSString alloc] is the alloc method call of the NSString class. This is a relatively low-layer call, which is used to allocate memory and instantiate an object.
[[NSString alloc] init] Call the init method of the newly created object. The init method usually performs object initialization settings, such as creating instance variables.
50. Memory Management
// string1 will be released automatically
NSString * string1 = [NSString string];
   
// Must be released manually after use
NSString * string2 = [[NSString alloc] init];
[string2 release];
51. The allocalloc method is called to allocate memory and instantiate an object. Call the init method of the newly created object to initialize and set the object, such as creating instance variables.
If you create an object by using manual alloc, you need to release this object. Similarly, you cannot manually release an autoreleased object because it will crash your application.
52. IBOutlet and IBAction if you want to see this control object in Interface Builder, add IBOutlet before definition to see the outlet of this object in IB, if you want to control an object to execute certain actions in Interface Builder, add (IBAction) before the method ).
Related interviews: 1. Does obj-c have multiple inheritance? Is there any alternative? All classes in cocoa are NSObject subclass multi-inheritance here is implemented using protocol delegate proxy. You don't have to consider the concept of complex multi-inheritance and virtual base class. the polymorphism of ood is implemented by delegation in obj-c.
2. Does obj-c have a private method? For private variables, there are only two methods in the objective-c-class: static and instance methods. this does not seem to be a complete object-oriented approach. According to the OO principle, an object only exposes useful things.

If there is no private method, it will not be easy to reuse some small-scale Code. It is a private method in the 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.

3. How to mix c and obj-c? 1. When the obj-c compiler processes files suffixed with m, it can recognize the code of obj-c and c, processing mm files can recognize obj-c, c, c ++ code, but cpp files must only use c/c ++ code, and in the header file of the cpp File include, the obj-c code cannot appear either, because cpp is only cpp.
2. Mix cpp in the mm file and use it directly. Therefore, obj-c Mixed cpp is not a problem.
3. Mixing obj-c in cpp is actually what we want to write modules using obj-c. 4. Target-action mechanism the target is the receiver of the action message. A control, or more commonly its unit, maintains the target of its action message in the form of a socket variable (see the "socket variable" section. 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.
5. What is the difference between # import and # include? What does @ class represent? @ Class is generally used when an instance variable of the class needs to be declared in the header file. # import is still required in the m file, and # the advantage of import over # include is that it will not cause Repeated inclusion.
6. how and how to manage the memory of Object-C? 1. When you create an object using the new, alloc, and copy methods, the reserved counter value of this object is 1. when you no longer use this object, you are responsible for sending a release or autorelease message to this object. in this way, the object will be destroyed at the end of its service life.

2. When you obtain an object through any other method, assume that the reserved counter value of this object is 1 and has been set to Auto Release, you do not need to perform any operations to ensure that the object is cleared. if you want to own this object for a period of time, you need to keep it and ensure that it is released when the operation is complete.

3. If you retain an object, You Need To (eventually) release it or automatically release it. You must ensure that the retain method and the release method are used equally.
7. What are the set methods and meanings of memory management Autorelease, retain, copy, and assign? 1. You need to release the (release) object you initialize (alloc/init. For example:
NSMutableArray aArray = [[NSArray alloc] init]; [aArray release];
2. You need to release retain or copy. For example:
[AArray retain] And then [aArray release];
3. objects to be passed (assign), retain and release you need to consider. For example:
obj2 = [[obj1 someMethod] autorelease];
When object 2 receives an automatically released value of object 1 or transmits a basic data type (NSInteger, NSString): You may want to retain object 2, to prevent it from being automatically released before being used. However, after retain, it is necessary to release it when appropriate.
Reference Counting
Retain value = index count (Reference Counting)
The NSArray object will retain (retain value plus one) any object in the array. When NSArray is detached (dealloc), all objects in the array are released once (the retain value is reduced by one ). Not only is it NSArray, but any Collection class performs similar operations. For example, NSDictionary or even UINavigationController. The index count of the objects created by Alloc/init is 1. You do not need to retain it again.
[NSArray array], [NSDate date], and other "methods" create an object with an index count of 1, but it is also an automatically released object. So it is a local temporary object, so it doesn't matter. If it is a variable (iVar) intended to be used in the whole Class, you must retain it. The "Auto Release" method is executed for the return values of the default class methods. (* NSArray in the preceding example), In the unload method "dealloc" in the class, all NS objects that are not balanced are release. (* All records that are not autorelisted and whose retain value is 1)
8. What is the difference between shallow copy and deep copy? In simple terms, in the case of pointers, the shallow copy only adds a pointer pointing to the existing memory, deep copy is to add a pointer and apply for a new memory so that the added Pointer Points to the new memory. When deep copy is used, when the memory is released, the same memory will not be released again during the shortest copy.
9. How to mix C and obj-c? 1. When the obj-c compiler processes files suffixed with m, it can recognize the code of obj-c and c, processing mm files can recognize obj-c, c, c ++ code, but cpp files must only use c/c ++ code, and in the header file of the cpp File include, the obj-c code cannot appear either, because cpp is only cpp.
2. Mix cpp in the mm file and use it directly. Therefore, obj-c Mixed cpp is not a problem.
3. Mixing obj-c in cpp is actually what we want to write modules using obj-c.
If the module is implemented as a class, write the class definition according to the cpp class standard. The header file cannot contain obj-c, including # import cocoa. In the implementation file, that is, the implementation code of the class can use obj-c and can be imported, but the suffix is mm.

If the module is implemented by functions, the header file should declare the function in the c format. In the implementation file, the c ++ function can use obj-c internally, but the suffix is still mm or m.


Summary: as long as the cpp file and the cpp include file do not contain obj-c, you can use it. The key to mixing cpp with obj-c is to use interfaces, instead, we cannot directly use modern real-time code. In fact, cpp is a mix of the o files compiled by obj-c. This is actually the same, so it can be used. The obj-c compiler supports cpp.

10. The difference between category and class extension in Objective-C: 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.
11. What does Objective-C mean by dynamic runtime language? 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 ).
So it can be said that the runtime mechanism is the basis of polymorphism?
12. What is the difference between Objective-C heap and stack? 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. Because of this, 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.






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.