CocoaStudy Notes DesignModeThe detailed description is the content to be introduced in this article. In this article, we will learn from many aspects.CocoaDesignModeLet's look at the content.
Enumerator
Similar to the iterator in the java container class, it is used to traverse elements in the class.
- NSDictionary *Mycollection;
- NSEnumerator *enumerator=[Mycollection objectEnumerator];
- while (instance=[enumerator nextObject]) {
- //
- }
The latest objective c introduces fast enumeration, as shown below:
- id instance;
- NSDictionary *Mycollection;
- NSEnumerator *enumerator=[Mycollection objectEnumerator];
- for (instance in Mycollection) {
- //
- }
The NSEnumerator class also supports fast enumeration. Therefore, you can use the following method to enumerate the data in the container in reverse order.
- id instance;
- NSArray *Mycollection;
- NSEnumerator *enumerator=[Mycollection objectEnumerator];
- for (instance in [Mycollection reverseObjectEnumerator]) {
- //
- }
To create a custom enumerator, you must inherit the NSEnumerator class. The important thing is the override nextObject method.
To implement quick enumeration, you must implement the NSFastEnumeration protocol, mainly by implementing the following methods:
- - (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)stackbuf count:(NSUInteger)len;
Execution selector and delayed execution
In cocoa, the method call of an object is performed in the form of a message. Therefore, the object needs to be able to execute an operation and send messages so that the object can start to execute an operation, content of the sent message
In cocoa, the selector is used to determine the message sent to the object, and the object receiving the message uses the selector to select the method to call.
- // Declare a selector and initialize it
-
- SEL aSelector = @ selector (application: didChangeStatusBarFrame :);
-
- // Declare that a selector is not initialized
-
- SEL bSelector;
-
- // Send selector to the object
-
- Id result1 = [Mycollection using mselector: aSelector];
-
- Id result2 = [Mycollection metrics mselector: @ selector (application: didChangeStatusBarFrame :)];
-
- // Check whether the object supports this method
-
- If ([Mycollection respondsToSelector: aSelector]) {
-
- // OK
-
- }
-
- // Dynamically create a class and selector
-
- Id class = [[NSClassFromString (@ "TestTableAppDelegate") alloc] init];
-
- [Class extends mselector: NSSelectorFromString ([NSString stringWithFormat: @ "setA % I", I])];
The basic principle of selector is that the apple Runtime Library quickly searches for the corresponding function pointer by buffering the IMP of each selector in the class itself, and you can also find the corresponding pointer by yourself.
- [Mycollection methodForSelector:aSelector];
- [NSDictionary instanceMethodForSelector:aSelector];
Archive and archive
To put it bluntly, it is object serialization.
- NSData * data = [NSKeyedArchiver archivedDataWithRootObject: self. window];
- // Default data access
- // Save it to the default data
- [[NSUserDefaults standardUserDefaults] setObject: data forKey: @ "window data"];
Similar technologies can be used to archive any objects that comply with the Protocol. The following is the definition of the Protocol. The first is used for archiving, and the second is used for archiving.
- @protocol NSCoding
-
- - (void)encodeWithCoder:(NSCoder *)aCoder;
- - (id)initWithCoder:(NSCoder *)aDecoder;
- @end
To support archiving and archiving, the object must implement the NSCoding protocol.
If the object inherits from the parent class, you must call the corresponding method of the parent class when implementing the NSCoding protocol, as shown below:
- @implementation TestClass
- @synthesize test1=_test1;
- static NSString *CodingKeyTest1=@"Test1";
- - (void)encodeWithCoder:(NSCoder *)aCoder{
- [aCoder encodeObject:self.test1 forKey:CodingKeyTest1];
- }
-
- - (id)initWithCoder:(NSCoder *)aDecoder{
- if (nil!=(self=[super initWithCoder:aDecoder])) {
- [self setTest1:[aDecoder decodeObjectForKey:CodingKeyTest1]];
- }
- return self;
- }
- @end
Example of cocoa single-State Mode
Many examples in the book are incorrect.
- Static TestClass * _ your instance = nil;
- -(Void) encodeWithCoder :( NSCoder *) ACO {
- _ Test2 = @ "test ";
- Self-> _ test2 = @ "test2 ";
- [Ecoder encodeObject: self. test1 forKey: CodingKeyTest1];
- }
- -(Id) initWithCoder :( NSCoder *) aDecoder {
- If (nil! = (Self = [super initWithCoder: aDecoder]) {
- [Self setTest1: [aDecoder decodeObjectForKey: CodingKeyTest1];
- }
- Return self;
- }
-
- (Id) hiddenAlloc {
- Return [super alloc];
- }
- // In single-State mode, objects cannot be created
- (Id) alloc {
- Return [[self defined instance] retain];
- }
-
- (Id) new {
- Return [self alloc];
- }
- (Id) allocWithZone :( NSZone *) zone {
- Return [[self defined instance] retain];
- }
- -(Id) copyWithZone :( NSZone *) zone {
- Return [[self defined instance] retain];
- }
-
- -(Id) mutableCopyWithZone :( NSZone *) zone {
- [Self copyWithZone: zone];
- Return self;
- }
- + (TestClass *) specify instance {
- If (_ your instance = nil ){
- _ Your instance = [[super allocWithZone: NULL] init];
- }
- Return _ response instance;
- }
Notification
Many examples in the book are incorrect.
The notification is the message listening response mode, which is similar to the implementation of MFC. The following is an example.
To receive messages to an object, you must register the object in the object notification center.
- Typedef struct {
- Int id;
- Float height;
- Unsigned char flag;
- } MyTestStruct;
- // Register the object to the message receiving Pump
- [[Nsicationcenter center defacenter center] addObserver: self selector: @ selector (textViewDidChangeSelection :) name:
- @ "NSTextViewDidChangeSelection" object: nil];
- // Code for processing the message received by the object
- + (Void) textViewDidChangeSelection :( NSNotification *) aNotification {
- NSValue * oldValue = [[aNotification userInfo] objectForKey: @ "search data with key value"];
- MyTestStruct _ teststruct;
- [OldValue getValue: & _ teststruct];
- NSLog (@ "% f print result", _ teststruct. height );
- }
- // Send a message to the object
-
- -(Void) postMessage {
- // Send a notification
- MyTestStruct _ teststruct;
- _ Teststruct. id = 0;
- _ Teststruct. height = 10.2;
- NSValue * _ value = [NSValue valueWithBytes: & _ teststruct objCType: @ encode (MyTestStruct)];
- NSDictionary * _ dic = [[NSDictionary alloc] initWithObjectsAndKeys: _ value, @ "search data with key value", nil];
- [[Nsnotifcenter center defacenter center] postNotificationName: @ "NSTextViewDidChangeSelection" object: self userInfo: _ dic];
- }
Delegate
To put it bluntly, it is the reference of another object.
For example, if A wants to send A message to B, A will save A reference to B's instance in A. Therefore, many cocoa classes have A non-type instance variable.
- id delegate;
For example, the window created by the resource file also has a delegate, which is connected to the delegate of a class, then the delegate of this class can be declared as follows:
- @property(nonatomic,readwrite,assign) IBOutlet id delegate;
You can also define a protocol-compliant delegate as follows:
- @property(nonatomic,readwrite,assign) IBOutlet id<UITableViewDelegate> delegate;
Outlet target action
The socket variable is used to connect to the instance created by the Nib file. After loading and initializing all objects from the nib file, the following message is sent to each object to be loaded:
- - (void)awakeFromNib;
After receiving the message, the object sets all its socket variables as values provided to them in Interface Builder.
The so-called goal is target. In cocoa, many classes provide a socket variable named target and an instance variable named action.
NSControl NSActionCell NSMenuItem implements the setTarget method to set the target
Any method that returns void and accepts an object parameter can be used as an action.
Use the setAction method to set actions
No matter what the action message is for, the NSApplication class-sendAction: to: from: method is used to complete sending.
The NSApplication class is a single-State class, so the following is generally used when sending an action:
- [[UIApplication sharedApplication] sendAction: to: from: forEvent:];
Responder chain
In cocoa, all objects that respond to user input are subclasses of the NSResponder abstract class.
When a user processes an application, cocoa automatically tracks the focus of the user. The window currently receiving keyboard input is called the "key" window, currently, documents with focus are referred to as "Main" documents, and the windows associated with the main documents are called "Main" windows. In cocoa, applications will automatically track the key windows and the main windows. The following methods are used to obtain references respectively.
- [[UIApplication sharedApplication] keyWindow];//iphone
- [[NSApplication sharedApplication] mainWindow] ;//macos
Call
Most people think that selector is the same as the message name. In fact, it is not completely because selector does not provide any type information, when constructing a message, you need to know the type of each parameter and the type of the returned value. This type of information is called method signature ).
The NSMethodSignature class encapsulates this information. The example is as follows:
- MyDocument *mydoc;
- NSMethodSignature *mySig=[mydoc methodSignatureForSelector:@selector(window:shouldDragDocumentWithEvent:from:withPasteboard:) ];
You can use NSInvocation to send a message, create an instance, and use it multiple times after configuration, and obtain the returned value. The specific instance will not be written. refer to the following URL.
Http://www.cnblogs.com/chenjunbiao/archive/2011/04/20/2022197.html
Share
The metadata is used to encapsulate non-object data so that it can be used in the context. When a large number of instances are required, the metadata reduces the storage requirements.
For example, NSNumber NSValue
NSDate;
- NSDecimalNumber;
- NSDate;
- NSCalendarDate;
- NSString;
- NSURL;
- NSFileHandle;
- NSPipe;
- NSAffineTransform;
All are share yuan
NSColor, NSFont; these meta-Cache and reuse objects
[NSColor redColor]; returns the same shared instance. The next request still uses the same instance.
Decorator
Is the combination between objects, reducing the number of classes, has-
Used to hide the mode of Complexity
Package
Is to package all the resources together.
Obtain the package of the executable program
- NSBundle *_budle=[NSBundle bundleForClass:[NSString class]];
Dynamically load executable code
- NSSearchPathForDirectoriesInDomains // function to obtain all the package paths
- _ Budle = [NSBundle bundleWithPath: @ "path"]; // dynamic package Loading
- BOOL isLoaded = [_ budle load]; // the executable code of the force package is linked to the application.
- Id class1 = [_ budle classNamed: @ "Class Name"]; // class in the access package
Category
The Class Cluster mode provides a simple interface for complex underlying implementation.
The main motivation of the class cluster is to avoid the complexity of internal implementation and provide simple interfaces as much as possible.
The technology used by the cluster-like mode depends on the two-phase Creation Mode of cocoa. The two phases are memory allocation and initialization.
After two-phase creation, the system first returns a pointer from + alloc to the storage space of the new instance that has not been initialized, and then initializes the new instance using a certain body of-id) init method.
Therefore, an instance of a subclass of a public interface may be returned through init. In the init method, release the allocated abstract base class instance first, then create an instance that can return the desired concrete subclass.
The method of class clustering provides simple interfaces, but complicate the creation of sub-classes.
Manager Mode
As the name suggests, a manager is a class for managing instances of other classes. NSFileManager NSFontManager NSInputManager NSLayoutManager in cocoa
In application design, there is usually a set of objects which must be unique, but they are not Singleton.
For example, a font can have a variety of different fonts, but the same font has an instance in the system.
Summary:CocoaStudy Notes DesignModeI hope this article will help you!