objective-c
A dynamic language, the dynamic two words are mainly reflected in the time we call the method, the runtime back to the dynamic lookup method, and then call the corresponding function address. The runtime is the cornerstone of the entire OBJECTIVE-C program, with which our programs can function properly.
NSObject is the base class for most of the classes in cocoa, and it mainly provides a sequence session, a copy object, and a framework that supports runtime dynamic recognition.
In addition, in OC, everything is a pointer.
At the beginning of each class object in Objective-c, there is an Isa pointer that points to an area of memory that contains two pieces of information:
1. A pointer to the parent class.
2, the method of their own publishing.
When we call a method of an object, we first look for the method in the current class's sub-publication, if the corresponding method is not found, and then go to its parent class to find the method, and so on until the corresponding method is found
The flowchart is as follows
You might think that if a class has a deep hierarchy of inheritance, it is not necessary to do many lookups every time a function of the root class is called. This is theoretically the case, but runtime is not so silly, it will maintain a list of frequently invoked methods for each class (not object), as long as the call is cached (the official does not explicitly state the caching mechanism), so that the process of the entire method call is more efficient when the program is running stably.
This article does not introduce the basic syntax of OC in detail:
OC base data type: http://www.cnblogs.com/GISerYang/tag/Objective-C/
Cocoa Frame
Cocoa provides the actual classes that hold the common data types for numbers and strings. These can be informally referred to as value classes or base value classes.
The cocoa framework itself encapsulates three separate frameworks: Foundation basic framework, AppKit framework, and core data framework
Foundation Framework
Provides basic building block classes, such as strings, arrays, numeric values, file accesses, and so on. This framework can be used on Mac and iphone OS (systems used on iphone, IPod touch, and ipad). The Foundation class makes it easier to deal with international texts and numbers, freeing programmers from a multitude of miscellaneous details.
AppKit Framework
Provides a framework that specifically handles user interface elements (for example, Windows, controls, fonts, and so on). The AppKit framework features the same functionality on the Mac as the Uikit on the iphone OS, all created around the same concept.
Core Data Framework
Provides data storage, data modeling, and automatic change of operational trajectory (also known as auto-reply or Redo). You can use SQLite, XML, binary storage types to hold data, or even create your own storage types.
informal agreement or class @interface with @implementation to @end
The declaration made between @interface and @end is an agreement to implement the method inside, but. m files @implementation to @end do not implement or compile errors.
So this gentlemen's agreement is an informal agreement with respect to the agreement @protocol.
In another way of understanding, interface and implementation collectively represent a class in which the class in OC must consist of two parts, interface parts and implementation parts;
The declaration portion of the member variable and member method is placed in the interface section, including the inheritance relationship, protocal implementation relationship, all in the interface inside the head to declare;
The implementation portion is placed in the implementation section, which is equivalent to splitting the class into declarations and implementations, both of which are indispensable.
@interface propertymodel:nsobject{ nsstring* sex; //No adornments, the default Protect property allows only this class and subclass to access . @public //All classes can be accessed, accessed in the form of pointers . @private nsstring* classes; //Private only this class can access . } @property (nonatomic,copy) nsstring* sexname; //accessible via Self.sexname . @end
Method starts with the '-' minus sign (OC does not differentiate between public and private), and relative to the ' + ' plus sign, it is a static member.
-(data type of the method return value) function name: (parameter 1 data type) parameter 1 of the variable name parameter 2 of the note name: (parameter 2 data type) parameter 2 value variable name ...;
Note: The OC method is visible except for the first parameter variable, each variable has a note name, and the invocation syntax is similar.
Public Property @property
A variable in a class is declared in parentheses in @interface:nsobject{}, and @property can be used to define a variable before it is @end after @interface: nsobject{} parenthesis.
If you define variables in @interface, the variables you define can only be accessed in the current class, not in other classes.
If you want to conveniently use the "self. Variable name" Point access method to read and write variables, and can be accessed outside the class, then the variable is set to the class's properties.
The role of the @property precompiled directives is to automatically declare the setter and getter methods of the property in the. h file .
@sythesize Create an access code for the property, the compiler adds precompiled code that implements the-setrainhandling: and-rainhandling methods.
@dynamic when attempting to invoke a non-existent getter and setter method, you will get an error.
Format:
@property (attribute) data type *name;
Use @property to indicate the property in. h and use @synthesize in. m to generate the appropriate accessors.
Extension of the property
- Assign//simple assignment, primarily for basic data types
- Copy//Create a new object, the new object and the old object are independent of two objects
- Retain//Add object counter to 1
- ReadOnly//indicates that a read-only property generates only getter methods and does not generate setter methods
- ReadWrite//default, table generation Setter and Getter method
- Nonatomic//non-atomic access, non-synchronous, multi-threaded concurrent access improves performance (protection against multithreading, preventing data errors when not written, read by another thread)
Protocol Protocol: Implementing a delegate with a protocol
Equivalent to C + + in the pure virtual base class, when writing Java will have interface interface this concept, interface is a bunch of methods of declaration is not implemented, and in OC, interface is a
The declaration of the header file of the class is not the meaning of the interface in the real sense, in OC, the interface is implemented by a protocol called a protocol. This inside
You can declare some methods, unlike Java, which can declare a number of methods that must be implemented and choose how to implement them. This is completely different from Java.
@optional and @required can be understood as virtual functions and pure virtual functions.
The implementation of the original method is, if B wants to let a work, let B do the boss in Class B declare an instance of a as a member variable, so B can be transferred to a method; but in OC, another kind of reverse thinking mode, B want to delegate A to do a thing to do a boss, in a, instance B, and then set a pointer to , B uses this pointer to invoke A's function, and these required functions are implemented by the B protocol for a compliance.
MyProtocol.h to declare protocol interfaces: Declaring methods only, not implementing them specifically
#import <Foundation/Foundation.h>@protocol myprotocol <NSObject>@optional // This method is optional -(void) Print: (int) value; @required// This method must be implemented -( int) Printvalue: (int) value1 andvalue: (int) value2; @end
The class that references the MYPROTOCOL protocol must implement the Protocol method as required
#import <Foundation/Foundation.h>#import"MyProtocol.h"@ Interface mytest:nsobject <myprotocol>-(void) showinfo; @end
Here's an example:
When a view is triggered to open B view (b is a modal view of a) and B view needs feedback to modify the interface of a view, then B will need to use the delegate.
In B, declare an agreement with the principal, and a principal pointer. A class that adheres to this protocol, implements these functions as required, implements an instance of a and points the principal pointer of B to itself for B to be called through a pointer.
In B You can check whether a function is implemented by the principal by the function [principal pointer respondstoselector: @selector (function name:)].
a_view.h: @interface:uiviewcontroller<b_viewdelegate>{ *myb_view;} @end a_view.m:-(void) viewwillappear: (BOOL) animated { //Will [Self.view Addsubview:myb_view]; } -(void) Ontouch: (ID) sender{ // Implementation Protocol B_ Viewdelegate Ontouch method for B call to modify a}
b_view.h:@protocolB_viewdelegate<nsobject>@optional-(void) Touch: (ID) sender;@end@interfaceb_view:uiviewcontroller{} @property (Nonatomic,retain)ID<B_ViewDelegate> touchdelegate;//principal pointer@endb_view.m:@synthesizetouchdelegate; - (ID) initWithFrame: (CGRect) Frame {if(self =[Super Initwithframe:frame]) {[Touchdelegate touch];//invoke the Protocol delegate, delegate to A_view to implement the function } returnSelf ; } @end
Category Categories
Encapsulation is a feature of object-oriented, OC is no exception, but sometimes we encounter a situation, such as we encapsulate a class, do not want to move it, but we need to add a method in that class, we do not have to modify in that class or define a subclass of it, You only need to add a category. Under the runtime mechanism of OC, java,c++ is a language with runtime mechanism. The--runtime mechanism is simply that the object type is not determined at compile time and is determined at run time. The category provides a more concise way to extend class than inheritance (inheritance), without having to create subclasses of the object class to add new methods to existing classes, and to add methods to any already existing class. Include classes that do not have source code (such as some framework classes).
There are 3 main functions of the category:
(1) The implementation of the class can be dispersed across multiple files or different frameworks for easy code management. You can also provide extensions of classes to the framework.
(2) Create a forward reference to a private method: If a method in another class is not implemented, the compiler will error when you access the private method of another class, then use the category, declare these methods in the category (without providing a method implementation), and the compiler will no longer generate a warning
(3) Adding an informal protocol to an object: Creating a nsobject category is called "Creating an informal protocol," because it can be used as a delegate object for any class.
For example: Add a Newfunc method to NSString, which features Mycompare as the unique name describing the purpose of the class, and embodies the idea of realizing it by category.
Category name Nsstring+mycompare.h
#import <Foundation/Foundation.h>@interface nsstring (mycompare)-(void ) test; @end
Category name NSSTRING+MYCOMPARE.M
#import " nsstring+mycompare.h " @implementation nsstring (Mycompare)-(void) newfunc{ }@end
For example: Asyncsocket this iOS socket plug-in. h file is to use the class purpose way to nsobject add the relevant socket function, reduce the plug-in Adoption protocol mode caused by the development trouble.
@interfaceNSObject (asyncudpsocketdelegate)- (void) Onudpsocket: (Asyncudpsocket *) sock Didsenddatawithtag: (Long) tag;- (void) Onudpsocket: (Asyncudpsocket *) sock Didnotsenddatawithtag: (Long) tag duetoerror: (Nserror *) error;-(BOOL) Onudpsocket: (Asyncudpsocket *) sock didreceivedata: (NSData *) data withtag: (Long) tag fromhost: (NSString *) host port: (UInt16) port;- (void) Onudpsocket: (Asyncudpsocket *) sock Didnotreceivedatawithtag: (Long) tag duetoerror: (Nserror *) error;- (void) Onudpsocketdidclose: (Asyncudpsocket *) sock;@end
iOS View Control
First, UIWindow is a special kind of uiview, usually in a program will only have a uiwindow, but you can manually create multiple UIWindow, and add to the program inside. UIWindow plays a major role in the process of three:
1, as a container, contains all the views that the app wants to display
2. Pass the touch message to the program view and other objects
3, with uiviewcontroller work together, to facilitate the completion of equipment direction rotation support
Second, there are usually two ways to add a view to the UIWindow:
1, Addsubview
The view is added directly to the window by Addsubview, the program is responsible for maintaining the view's life cycle and refreshing, but not for the viewcontroller of the view, so after adding the view to the window in this way, We also need to maintain the validity of the viewcontroller of the view and not release it prematurely.
2, Rootviewcontroller
Rootviewcontroller a traversal method of UIWindow, by setting this property to add a view corresponding to the Viewcontroller,uiwindow will automatically add its view to the current window, Also responsible for Viewcontroller and view life cycle maintenance to prevent premature release
Third, Windowlevel
The UIWindow will be sorted according to Uiwindowlevel when displayed, that is, the level will be in front of all levels below him. The level of high and low order from small to large for normal < StatusBar < Alert, this means that when the level levels are the same, only the first set to Keywindow display, the subsequent sibling Keywindow will not be displayed. (Keywindow is a specified message to receive a keyboard and a non-touch class, and only one window per time in a program is Keywindow)
Iv. numerous views in the Uiviewcontrol management program
The view is best to load when it needs to be displayed, and to release the necessary view and related data objects when the system issues a memory warning.
1, the initialization will call Init,initwithcoder and other related functions as needed, this time we can do a simple initialization operation, the establishment of VIEWCONTROLLER data model needed to use, etc.
It is not recommended that you create the view and other display-related objects directly during the initialization phase (which should be put to loadview or created with lazy loading) Viewcontroller can be created in code and xib two ways, both of which have different initialization processes.
1) VC created with Xib
Xib actually will save our settings as a data set, when the need to initialize the VC, go back to read the recorded data set, and then help us to create a dynamic VC, so you can imagine it will be initialized to see if the implementation of the Initwithcoder method, if the class implemented the method, The Initwithcoder method is called directly to create the object, and if not implemented, the Init method is called. The Awakefromnib method is called immediately after the initialization method is called, and in this method we can do further initialization operations.
2) Create VC using code
When using code creation, we manually create the data in the VC as needed, and if you customize the VC, you also need to invoke [super Init] in init.
2. Load and unload life cycle of view in Uiviewcontroller
It is not recommended to create a view and other display-related code at the time of VC initialization, and the official documentation suggests that the initial operation of the view should be placed in the Loadview. When the VC receives a memory alarm call didrecievememorywarning This time we are going to respond and release temporarily unwanted objects. If this warning is ignored, the system will continue to be sent when memory is insufficient, forcing the program to quit if it is not processed. See below the specific Loadview and unloadview what to do when the operation.
1) Load Cycle
When the view property needs to be displayed or accessed, the VC calls the Loadview method, at which point it creates a view and assigns it to the Vc.view property. Then the VC Viewdidload method is called, this time the Vc.view guarantee is a value, you can do further initialization operations, such as adding some subview. Note: If you override the Loadview method when customizing the VC, you do not need to call the [Super Loadview] method.
2) Unload cycle
When the app receives a memory warning, it calls the Didrecievememorywarning method of each VC, and we need to respond to releasing resources that are temporarily not needed in the program. This method is often overridden, overriding the need to call super. If a view of the current VC is detected to be released safely, the Viewwillunload method is called and its subviews may be released together when the VC's view disappears. After calling Viewwillunload, the Vc.view property is set to nil, and then when the Viewdidunload method is called, we can release those strongly referenced objects.