Basic OC programming skills-required for iphone Development

Source: Internet
Author: User
Tags file url
Document directory
  • Root class and Objective-C object
  • Create object
  • Think in terms of Objects
  • Manage object graphs to avoid Memory leakage
  • Management object Variability
  • Create and use value objects
  • Create and use groups
  • Measure the object capability during running.
  • Comparison object
  • Copy object

Basic OC programming skills

As its name implies, the Foundation framework is a basic tool for all iOS and Mac OS X programming. To become a successful developer on these two platforms, you must be familiar with this tool.

The Foundation framework defines a large number of classes and protocols that perform their respective duties. However, the three types and protocols are more prominent, and they are the most basic part:

  • The root class and related protocols.The root class, that is, NSObject, is accompanied by a protocol with the same name. It identifies the basic interfaces and actions of all Objective-C objects. There are also some protocols that other classes can use to copy the instances of these classes and encode their statuses.
  • Numeric type.A value class can generate an instance (called a value object), which is an object-oriented packaging that encapsulates basic types of data such as strings, numbers, dates, and binary data.
  • Group class.An instance of a group class (called a group) manages a group of objects. To distinguish different types of groups, we need to see how to access the objects it contains. Generally, projects in a group are a series of numerical objects.

Groups and numeric objects are extremely important in Objective-C programming because they are often used as parameters and return values of methods.

Root class and Objective-C object

In class inheritance, the root class does not inherit from other classes, and all other classes are ultimately inherited from the root class. NSObject is the root class in Objective-C inheritance. All other classes inherit a set of basic interfaces from NSObject to the Objective-C runtime system. Instances of these classes are inherited from NSObject to obtain the most fundamental features of Objective-C.

But for itself, NSObject instances cannot do anything interesting, but at most they are just objects. To use more attributes and logic to customize your program, you must create one or more classes that inherit from NSObject, or use existing classes that directly or indirectly inherit from NSObject.

NSObject adopts the NSObject protocol, which declares some additional methods that can be used by all object interfaces. In addition, NSObject. h (including the header file defined by the NSObject class) contains the NSCopying, NSMutableCopying, and NSCoding protocols. When a class adopts these protocols, it obtains the basic object behavior of object copy and object encoding. Model classes (classes that encapsulate application data and manage instances of such data) often use object copy and object encoding protocols.

The NSObject class and related Protocols define a series of methods for creating objects, browsing inheritance chains, viewing object features and functions, comparing objects, copying objects, and encoding objects. This article focuses on the basic requirements of such tasks.

Create object

Generally, when creating an object, you must first allocate memory for it and then initialize it. Although they are two separate steps, they are very confidential. Some classes can create objects by calling their factory methods.

Create object-allocate memory and initialize

To allocate memory to an object, send an alloc message to its class to obtain an "original" (uninitialized) instance of the class. When you allocate memory for an object, the Objective-C Runtime reserves enough memory space for the object in the virtual memory of the application. In addition to memory allocation, this step also has several other functions, such as setting all instance variables to 0.

After the memory is allocated to the original Instance, you must initialize it. Initialization is to set the object to the initial state. In other words, it is to set its instance variables and attributes to reasonable values and then return this object. The initialization is to ensure that the returned object can be used.

You will find that many frameworks containInitializers(Initiator) method, that is, the method that can initialize the object. Most of them are similar. The initialization tool is an instance method. The method starts with init and returns an id-type object. The root object NSObject declares the init method. All other classes inherit this method. Other classes can also declare their own initiators. Each class must have its own keyword and parameter type. For example, the NSURL class declares the following initiators:

-(Id) initFileURLWithPath :( NSString *) path isDirectory :( BOOL) isDir

When you allocate memory for an object and initialize it, You can nest the memory allocation method and initialization method. If you use the above initiator, you can write it as follows:

NSURL * aURL = [[NSURL alloc] initFileURLWithPath: NSTemporaryDirectory () isDir: YES];

As a Secure Programming habit, you can check the returned object to verify that the object is created correctly. If the object fails to be created due to an accident during the creation process, the nil is returned by the initiator. Although Objective-C allows sending messages to nil without any side effects (for example, throwing an exception), your code obviously cannot work normally because there is no way to call it. Instead of using the instances returned by alloc, you must use the instances returned by the initialization tool.

Create an object by calling the factory method of the class

You can create an object by calling the factory method of the class. The factory method is a type of method that can allocate memory, initialize, and return the instance itself. The factory method of class is a convenient method, because they only need one step to create objects, rather than the two steps mentioned above. Their form is as follows:

+ (Type)ClassName... (HereClass NameDoes not contain any prefix)

Some classes in the Objective-C framework define a factory method, which actually acts as the initialization tool. For example, NSString declares the following two methods:

-(Id) initWithFormat :( NSString *) format ,...;

+ (Id) stringWithFormat :( NSString *) format ,...;

The following example shows how to use the NSString factory method:

NSString * myString = [NSString stringWithFormat: @ "Customer: % @", self. record. customerName];

Think in terms of Objects

At runtime, each application is composed of a group of objects that collaborate with each other. These objects can communicate with each other to complete the work required by the application. Each object has its own role, at least responsible for one thing, and at least one other object is connected. (Isolated objects have no value .) As shown in, there are both framework objects and application objects in the network composed of objects. An instance of a custom subclass when an application object is created. It generally inherits from a parent framework. Networks composed of these objects are generally called object graphs.

You need to create these connections or links and reference them between objects. There are many referenced language forms, including instance variables, global variables, and even local variables (within a limited scope. The relationship can be a one-to-one or one-to-many relationship, which can represent the concept of a series of subordination. These relationships are the means by which an object can access, communicate, or control other objects. The referenced object naturally becomes the receiver of the message.

Messages transmitted between objects of an application are an important factor for the application to continue working. Like a performer in an orchestra, each object in an application has its own role and fulfills its own responsibilities for the operation of the application. Some objects can display an elliptical interface response point by action, some manage data sets that carry various data, and some control the major events throughout the application lifecycle. However, in order to complete their respective tasks, they must be able to communicate with each other. Each object must be able to send messages to other objects in the same application, and receive messages from other objects.

Some objects are closely paired, that is, they are directly connected to each other. It is easy to send messages to each other. But there are still some non-closely paired objects, that is, the objects separated in the object graph. to communicate between them, we need to find another way. The Cocoa and Cocoa Touch frameworks contain many functions and mechanisms to help non-closely paired objects communicate, as shown in ). These mechanisms and technologies are built on some design patterns (we will discuss them later), which makes the application more efficient and super scalable.

Manage object graphs to avoid Memory leakage

Objects in the Objective-C program form an object graph: a network formed by the relationship (or reference) between each object and other objects. References between objects are divided into one-to-one and one-to-many (through object sets) references. An object graph is very important because it is a key factor to keep objects alive. The compiler checks the reference strength in the object graph and keeps the object message sent or released as needed.

In C or Objective-C, you can use a structure containing global variables, instance variables, or local variables to construct references between objects. Each of these structures has its own scope. For example, the scope of an object referenced by a local variable is the location where the function block of the object is declared. It is equally important that references between objects are also weak. A strong reference will indicate who the owner is, and point to the object of another person who owns the object to which the object is directed. A weak reference indicates that there is no subordination between the object pointing to another person and the object being pointed. The lifecycle of an object is determined by the number of strongly referenced objects. As long as the object has a strong reference relationship, it will not be released.

References in Objective-C are strongly referenced by default. In general, this is very convenient, allowing the compiler to manage the runtime lifecycle of objects. They will not be released when you use objects. However, if carelessness is not fully checked, strong references between objects may form an infinite loop, as shown on the left. Such a loop chain will cause no objects to be released during the runtime, and they all point to their own strong references. In this case, memory leakage occurs.

For the objects in the figure, if you cancel the reference between A and B, the sub-object graph composed of B, C, D, and E will not be released from the memory "forever, each of these objects has a strong reference, forming an endless loop. If weak references are introduced between E and B, the infinite loop of strong references can be broken.

To fix the issue of strong reference endless loops, savvy programmers will use weak references. The weak reference of the object is continuously tracked during running. Once the object no longer has a strong reference, the runtime will release the object and change all references pointing to the object to nil. For variables (global, instance, and local variables), you can mark them as weak references by adding a _ weak prefix to the object name. You can use the weak option for attributes. In the following types of references, you should use weak references:

  • Delegate

    @ Property (weak) id delegate;

    In the "design patterns" section, the "using design patterns to streamline application development" tutorial will explain the delegation and target mechanism to you.

  • Outlet variables not referenced by top-level objects)

    @ Property (weak) IBOutlet NSString * theName;

    A socket variable is a connection (or reference) between objects and is archived in a story or nib file. When an application runs and loads a story or nib file, the socket variable is restored. The socket variables of top-level objects in the story or nib files are generally windows, views, view controllers, or other controllers. They should be strongly referenced (default, or unmarked ).

  • Target

    (Void) setTarget :( id _ weak) target

  • References to self in the block object

    _ Block typeof (self) tmpSelf = self;
    [Self methodThatTakesABlock: ^ {
    [TmpSelf doSomething];
    }];

    The block object generates a strong reference to the variables it captures. If you use self in the block object, it will generate a strong reference to self. Therefore, if self has a strong reference to the block object (usually this way), it forms an infinite loop of strong reference. To avoid endless loops, you need to create a weak (or _ block) Reference pointing to self outside the block object, as shown in the preceding example.

Management object Variability

A mutable object is an object that can change its status after being created. In general, you need to use attributes or access methods for changes. An unchangeable object is an object that is encapsulated after being created and whose status cannot be changed. The instances of most classes created in the Objective-C framework are variable, but there are several immutable classes. Immutable objects have the following advantages:

  • When using an immutable object, Do not worry that its value will change unexpectedly.
  • For many types of objects, immutable objects can improve the performance of applications.

In the Objective-C framework, instances of immutable classes are typically encapsulated sets of discrete values or buffer values, such as arrays and strings. These classes usually have a variable callback class, and the class name is"Mutable"(Variable. For example, there is an NSString class (immutable) and NSMutableString class. It should be noted that for NSNumber or NSDate objects that encapsulate discrete values, there is no need to have a variable sequence class.

If you need to change the object content frequently, you can use a mutable object instead of an immutable object. If the object you receive from the Framework is an immutable object, follow the returned type and do not try to change the object content.

Create and use value objects

A value object is an object that encapsulates (C language type) Basic data type values and provides a series of functions related to this value. The value object represents the scalar type in the object table. The Foundation framework provides the following classes for you to generate string, binary data, date and time, and numeric equivalent objects:

  • NSString and NSMutableString
  • NSData and NSMutableData
  • NSDate
  • NSNumber
  • NSValue

Value objects are very important in Objective-C Programming, because applications call these objects as parameters and return values of methods and functions. By passing value objects, each part of the framework can even exchange data between different frameworks. Because value objects represent scalar values, you can use them in a set or other places where you need to use objects. In addition to having the same features of common data types and necessary components for programming, value objects also have greater advantages: you can operate these encapsulated values in a more effective and elegant way. Take the NSString class as an example. It provides methods for searching and replacing strings, writing strings to files or (more commonly used) URLs, and building file system paths.

In some cases, you may think that using basic data types is more effective and direct, such as int (integer type) and float (floating point type. A specific example is to calculate a value. Therefore, NSNumber and NSValue objects are rarely treated as parameters and return values of methods in the framework. However, it should be noted that many frameworks declare their own numeric data types and pass and call these data types as parameters and return values, such as NSInteger and CGFloat. You need to use the data types defined by these frameworks in the appropriate scenarios to help you extract the code and stay away from the underlying platform.

Basic methods for using value objects

The basic mode for creating a value object is to create a value object for your code or framework code using the basic data type value (it may be passed as a method parameter later ). In your code, you will soon access the encapsulated data in the object. It is no longer appropriate to use the NSNumber class for example:

Int n = 5; // value assignment of the basic data type
NSNumber * numberObject = [NSNumber numberWithInt: n]; // create a value object using the basic data type
Int y = [numberObject intValue]; // obtain the encapsulated value (y = n) from the value object)

Most "value" classes declare an initiator and the factory method used to create an instance. Some Classes-for example, NSString and NSData not only provide the initiator, but also the factory method for creating an instance by using data stored locally, remote files, or even in memory. These classes also provide complementary methods to write string and binary data to a location specified by a file or URL. The following sample code demonstrates initWithContentsOfURL: The method creates an NSData object using the content of the file specified in a URL object. After using the data, the Code writes the data object back to the file system:

NSURL * theURL = // code that uses the string path to create the File URL...
NSData * theData = [[NSData alloc] initWithContentsOfURL: theURL];
// Use the obtained data...
[TheData writeToURL: theURL atomically: YES];

In addition to creating value objects and allowing you to access encapsulated values, most value classes also provide a series of simple operations, such as comparing objects.

String

As a superset of the C language, Objective-C uses strings in the same way as C. In other words, a single letter is enclosed in single brackets, and a string is enclosed in double brackets. However, the Objective-C framework generally does not use a C-style string, but uses an NSString object.

In your first iOS app tutorial, you created a formatted string when writing a HelloWorld app:

NSString * greeting = [[NSString alloc] initWithFormat: @ "Hello, % @!", NameString];

The NSString class provides an object package for strings. Therefore, it provides memory management functions with variable-length string storage, supports many character encoding (especially Unicode encoding), and printf-style formatting syntax. Because you often use strings, Objective-C provides a shortcut for creating NSString objects using constants. To use this shortcut, you only need to add the @ symbol to the front of the string enclosed in regular double quotes, as shown in the following example:

// Create the String "My String" with a line break
NSString * myString = @ "My String \ n ";
// Create a formatted String "1 String"
NSString * anotherString = [NSString stringWithFormat: @ "% d % @", 1, @ "String"];
// Use a C-language string to create an Objective-C string
NSString * fromCString = [NSString stringWithCString: "a c string" encoding: NSASCIIStringEncoding];

Time and date

The NSDate object is different from other value objects because it is essentially a time rather than a basic data type. A date object uses the reference time to encapsulate an interval value in seconds. The reference time is the first instance in GMT January 1, 2001.

The NSDate instance alone may not be very useful. It does represent a certain time, but it does not have much significance without calendar, time zone, and time conventions of individual regions. Fortunately, the Foundation class provides entities for these concepts:

  • NSCalendar and NSDateComponents: You can associate a date with a calendar, including the extended time unit, such as a day in a year, month, hour, or week. You can also calculate the date.
  • NSTimeZone: When the date and time must reflect the time zone of a region, You can associate the time zone object with the calendar.
  • NSLocale: a localized object that encapsulates time-related cultural and language format conventions.

The following code snippet shows how to use the NSDate object together with the above objects to obtain the information you need (in this example, the current time is printed in the format of hour, minute, second ). Please refer to the comment behind the corresponding numeric item below the code segment:

NSDate * now = [NSDate date]; // 1
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; // 2
[Calendar setTimeZone: [NSTimeZone systemTimeZone]; // 3
NSDateComponents * dc = [calendar components :( NSHourCalendarUnit | NSMinuteCalendarUnit |
NSSecondCalendarUnit) fromDate: now]; // 4
NSLog (@ "The time is % d: % d", [dc hour], [dc minute], [dc second]); // 5

  1. Create a date object that represents the current time.
  2. Create an object that represents the Gregorian calendar.
  3. Set the time zone of the Calendar Object by using the object that represents the time zone set in the system preference settings.
  4. Call the components: fromDate: Method of the Calendar Object to pass the date object created in step 1 as a parameter. After this method is called, an object containing the hour, minute, and second elements of the time object is returned.
  5. Print the current time, minute, and second on the console.

Although this example finally prints the results, we recommend that you use the date formatter (NSDateFormatter class instance) to display date information on the application interface. You must use the correct classes and methods for date calculation. Do not hard encode the time, minute, second, day, and other numeric units.

Create and use groups

A group is also an object that can store other objects in a specific way and allow customers to access those objects. You usually pass groups as parameters of methods and functions, and often obtain a group from the return values of methods and functions. A group usually contains value objects, but they can contain any type of objects. Most groups produce strong references to the objects they contain.

There are several groups of Foundation frameworks, three of which are extremely important in Cocoa and Cocoa Touch programming: arrays, dictionaries, and collections. Classes of these groups also have immutable and mutable forms. A mutable group can add and remove objects. An Immutable group can only contain objects contained during creation. All groups can be enumerated, that is, to check each object in turn.

Different groups organize the objects they contain in different ways:

  • NSArray and NSMutableArray: arrays are a series of objects stored in order. You can find an object by its position number (that is, its index ). The index of the first object in the array is 0 (number 0 ).
  • NSDictionary and NSMutableDictionary: The dictionary stores entries in the form of Key-Value pairs. A key is a unique identifier, usually a string. A value is the object you want to store. You can directly access the corresponding object through the key.
  • NSSet and NSMutableSet: objects in the set are stored unordered and each object can only appear once. When you want to access one or more objects in a set, you must filter or determine the objects.

Because of their different storage, access, and performance, they have their own advantages and disadvantages in different scenarios.

Store objects in a specific sequence in an array

Objects in the array are stored in order. Therefore, you can select an array when the order is important. For example, many applications use arrays to store content in the table view or items in the menu. Objects with an index value of 0 represent the first row, and objects with an index value of 1 correspond to the second row, and so on. The object access speed in the array is slightly slower than the access speed of the set.

The NSArray class has multiple initiators and class factory methods used to create and initialize arrays. Several of them are particularly common. You can use a series of objects to create arrays and use arrayWithObjects: count: And arrayWithObjects: methods (and their corresponding Initiators. The second parameter of the method on the front can be used to limit the number of objects in the first parameter. In the method on the back, you can use nil to abort a series of objects separated by commas.

// Create a static array containing string objects
NSString * objs [3] ={@ "One", @ "Two", @ "Three "};
// Create a new array object with this static object
NSArray * arrayOne = [NSArray arrayWithObjects: & (* objs) count: 3];
// Create an array of object lists ending with nil
NSArray * arrayTwo = [[NSArray alloc] initWithObjects: @ "One", @ "Two", @ "Three", nil];

When creating a mutable array, you can use the arrayWithCapacity :( or initWithCapacity :) method to create this array. The capacity parameter is only the default value of the expected array size, which makes the array more efficient at runtime. That is to say, the actual size of the array can exceed the specified capacity.

Generally, you need to call objectAtIndex to access objects in the array through the index position (starting from 0:

NSString * theString = [arrayTwo objectAtIndex: 1]; // returns the second object in the array.

NSArray has other methods. You can access objects in the array or their indexes. For example, lastObject, firstObjectCommonWithArray: And indexOfObjectPassingTest: methods.

Another important function of arrays is to operate every object in the array. This process is called enumeration. You usually enumerate an array to determine whether an object meets a certain value or condition. If the condition is true, you can perform further operations. There are three enumeration methods available: Quick enumeration, block object enumeration, or NSEnumerator object. As shown in its name, quick enumeration is generally faster than other enumeration methods in obtaining objects in an array. Quick enumeration has its own Syntax:

For(Type variableInArray){/* ProvisionVariableAnd perform the required operations */}

For example:

NSArray * myArray = // get the Array
For (NSString * cityName in myArray ){
If ([cityName isw.tostring: @ "Cupertino"]) {
NSLog (@ "We're near the mothership !");
Break;
}
}

There are several NSArray methods that use block objects for enumeration. The simplest one is enumerateObjectsUsingBlock :. A block object has three parameters: the current object, its index value, and a Boolean value. If it is YES, the enumeration ends. The effect of the Code in the block object is exactly the same as that in the quick enumeration in curly brackets:

NSArray * myArray = // get the Array
[MyArray enumerateObjectsUsingBlock: ^ (id obj, NSUInteger idx, BOOL * stop ){
If ([(NSString *) obj isEqualToString: @ "Cupertino"]) {
NSLog (@ "We're near the mothership !");
* Stop = YES;
}
}];

NSArray also provides methods for sorting arrays, searching, and acting on each object in the array.

To add an object to a variable array, call addObject: method. The newly added object is placed at the end of the array. You can also use insertObject: atIndex: to place an object in a specific position in the array. You can remove an object from the array by calling removeObject: Or removeObjectAtIndex.

Store key-value pairs with dictionaries

The dictionary can store objects in the group as key-value pairs. A key-value pair is a pair composed of an identifier (key) and an object (value. Dictionaries are unordered because key-value pairs can be stored in any order. Although the key can be in any form, it is best to describe the value string, such as NSFileModificationDate or UIApplicationStatusBarFrameUserInfoKey (both string constants ). When they are public keys, it is better to use dictionaries to transmit information between any type of objects.

Through its initiator and class factory methods, the NSDictionary class has many dictionary creation methods, but two of them are the most commonly used: dictionaryWithObjects: forKeys: and dictionaryWithObjectsAndKeys: (or their corresponding Initiators ). In the previous method, you need to input an array of objects and a key array. Keys and values must correspond to each other in the position. In the next method, you need to specify the first object value and its key, the second object value and its key, the third and fourth, and so on; nil can be used to end this object series.

// Create an array of keys and a complementary array of values.
NSArray * keyArray = [NSArray arrayWithObjects: @ "IssueDate", @ "IssueName", @ "IssueIcon", nil];
NSArray * valueArray = [NSArray arrayWithObjects: [NSDate date], @ "Numerology Today ",
Self. currentIssueIcon, nil];
// Create a dictionary and input the key array and value Array
NSDictionary * dictionaryOne = [NSDictionary dictionaryWithObjects: valueArray forKeys: keyArray];
// Create an Array Using values and keys in turn and use nil to end the dictionary
NSDictionary * dictionaryTwo = [[NSDictionary alloc] initWithObjectsAndKeys: [NSDate date],
@ "IssueDate", @ "Numerology Today", @ "IssueName", self. currentIssueIcon, @ "IssueIcon", nil];

To access the object Value in the dictionary, you must call objectForKey: method and specify a key in the parameter.

NSDate * date = [dictionaryTwo objectForKey: @ "IssueDate"];

You can call setObject: forKey: to add an entry to the variable dictionary, use removeObjectForKey: to delete an entry, and use setObject: forKey: to replace the value corresponding to any given key. These methods run quickly.

Use a set to store unordered objects

The set is similar to the array but the entries in the set are unordered. You cannot access the objects in the set through indexes or keys, but randomly access (anyObject). You can find objects by enumerating groups or using filters or tests.

Although the integration of objects in Objective-C is not as common as dictionaries and arrays, they are still very important group types in some technologies. In Core Data (a Data management technology), when you declare a one-to-many relationship attribute, the attribute type should be NSSet or NSOrderedSet. Collection is also very important in processing native touch events in the UIKit framework, such:

-(Void) touchesEnded :( NSSet *) touches withEvent :( UIEvent *) event {
UITouch * theTouch = [touches anyObject];
// Process the code ......
}

An ordered set is a special case beyond the definition of a set. In an ordered set, the order of entries is very important. To test whether an entry exists, the ordered set is faster than the array.

Measure the object capability during running.

Introspection is a powerful and practical feature of the NSObject class in Objective-C. It allows you to get information about objects at runtime. In this way, you can avoid some errors, such as sending a message to an object that does not know it, or thinking that an object inherits from another object, but it is actually not.

At runtime, an object can convey three important types of information about itself.

  • Whether it is an instance of a class or subclass
  • Whether it can respond to a message
  • Whether it complies with a certain agreement

Whether the inquiry object is an instance of a class or its subclass

In this way, isKindOfClass is called for the object: method:

Static int sum = 0;
For (id item in myArray ){
If ([item isKindOfClass: [NSNumber class]) {
Int I = (int) [item intValue];
Sum + = I;
}
}

IsKindOfClass: The method requires a Class object as a parameter. To obtain this object, you can call the class method on the Class symbol. Check the Boolean value returned by this method and perform the next operation.

NSObject also declares other methods to explore Object Inheritance Information. For example, isMemberOfClass: The method will tell you whether the object is an instance of a specified class, And isKindOfClass will tell you whether the object is a member of a class or its subclass.

Whether the query object can respond to a message

To do this, call respondsToSelector for the object: method:

If ([item respondsToSelector: @ selector (setState :)]) {
[Item setState: [self. arcView. font isBold]? NSOnState: NSOffState];
}

RespondsToSelector: The method requires a selector as the parameter. A selector is a data type of Objective-C. You can identify a method at runtime. You can use the @ selector compiler command to specify this selector. In your code, check the Boolean value returned by this method and perform the next operation.

To identify the message to be sent to an object, call respondsToSelector: method, which is more useful than the detection class type. For example, the latest version of a class may implement a method that does not exist in the old version.

Whether the query object complies with a certain protocol

To do this, call conformsToProtocol on the object: method:

-(Void) setDelegate :( id _ weak) obj {
NSParameterAssert ([obj conformsToProtocol:
@ Protocol (subviewtableviewcontrollerperformanceprotocol)]);
Delegate = obj;
}

ConformsToProtocol: The method requires the runtime identifier of the protocol as a parameter. You can specify this identifier using @ protocol compiler instructions. Next, check the Boolean value returned by the method and perform the next operation.

Comparison object

IsEqual: The method can be used to compare two objects. The objects that receive this message will be compared with the objects passed in as parameters; if they are the same, YES will be returned for this method. Example:

BOOL objectsAreEqual = [obj1 isEqual: obj2];
If (objectsAreEqual ){
// Perform some operations...
}

Note that the equality of objects is not the same as that of objects. The object's identity must be == to check whether two variables point to the same instance.

So when you compare two objects, what are you comparing? This depends on the specific class. The root NSObject class uses pointer equality as the basic point of comparison. Sub-classes at any level can override the implementation of the basic points of the parent class comparison according to the conditions of the specific class, such as the object state. For example, assume that there is a Person object and another Person object. If their last names, names, and birthday attributes are the same, they are considered equal.

The value and Group Object of the Foundation framework declare the comparison method in the form of isdomaintotype :.TypeIs the class name that removes the "NS" prefix, such as isw.tostring: And isw.todictionary :. The comparison method can be used to determine whether the input object is suitable for a given type for other forms of comparison.

Copy object

To copy an object, call the copy method:

NSArray * myArray = [yourArray copy];

As a Copied object, the class of the object receiving the message must comply with the NSCopying protocol. To make the object copy, you must use the copy method of this Protocol and implement it.

If you need to use an object in another place of the program and want to fully maintain the state of the object, you need to copy the object.

The copy behavior is different based on different classes, and also depends on the characteristics of individual instances. Most classes implement deep copy, which copies all instance variables and attributes in the instance. Some Classes implement shallow copy, which only copies instance variables and attribute references.

A mutableCopy method is also declared for classes with mutable and immutable variants to create a variable copy of an object. For example, if you call the mutableCopy method for an NSString object, you will get an NSMutableString instance.

Turn: http://www.guomii.com/posts/23681

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.