Classes in OC are mutable and immutable. The following table lists the main mutable and immutable classes in the Foundation framework:

species

Immutable classes

The variable class

An array of

NSArray

NSMutableArray

data

NSData

NSMutableData

The dictionary

NSDictionary

NSMutableDictionary

A collection of

NSSet

NSMutableSet

string

NSString

NSMutableString

String with attributes

NSAttributedString

NSMutableAttributedString

Character set

NSCharacterSet

NSMutableCharacterSet

The index set

NSIndexSet

NSMutableIndexSet

Mutable object generation:

Mutable classes are subclasses of immutable classes, so instance objects of mutable classes can be directly used as instance objects of immutable classes. In contrast, if you want to use an instance object of an immutable class as an instance object of a mutable class, you can use the mutableCopy method to create a mutableCopy of the immutable object.

– (id)mutableCopy

String class NSString

Constant string:

Nsstrings * name = @ “chenzhen”;

Strings defined in this way are constant objects that can be used as objects of NSString. You can be both the parameter of the message and the receiver of the message.

@ “” represents an empty string, but it’s different from nil.

When compiled, the compiler concatenates whitespace separated strings:

Nsstrings * name = @ “Chen” @ “” @” zhen “;

String constants exist from the start to the end of program execution, and cannot be released by calls to release or garbage collection.

Nsstrings:

Instances of NSString and NSMutableString are called string objects or strings. String objects use Unicode encoding internally.

Advantages of treating strings as objects:

Many operations can be unified

The logic for generating releases is the same

NSString also defines a lot of common methods

Because NSString is implemented as a class cluster, you cannot subclass NSString in the usual way.

In the instructions for initializing methods, class methods that use a combination of alloc and init to generate and return instances are marked as convenience constructors. The main methods of NSString are described below:

(1) Operate on Unicode encoded strings

Chinese characters in NSString are represented in Unicode. The Unicode utf-8 encoding is compatible with the ASCII 7bit encoding. If the string contains only the ASCII 7bit encoding, the ASCII string is treated as a utf-8 Unicode string, not as a utf-16 string.

– (

Id)initWithUTF8String:(constchar*)bytes// copies the information from the null-terminated utf-8-encoded c string and initializes the receiver. Convenience constructor: stringWithUTF8String:

– (

__strongCONSTCHAR *)UTF8String// Returns a pointer to a null-terminated C string encoded as UTF. In memory management mode based on reference counting, the returned string is freed at the same time the message receiving object is freed. In memory management mode, garbage collection is not garbage collected because strong Pointers are returned.

– (NSUInteger)length

// Returns the number of characters.

– (unichar)characterAtIndex:(NSUInteger)index

// returns the character with index I. Unichar is a two-byte char that represents a unicode character.

–  (id)initWithCharacters:(const unichar *)characters length:(NSUInteger)length

// Use characters to initialize the length string stored in characters and return an NSString object. Initialization is based on length, and characters can’t be used as an end flag even if they include ‘\0’. Convenience constructor: stringWithCharacters: length

–  (void)getCharacter:(unichar *)buffer range(NSRange)aRange

//NSRange is a range structure that includes the first pointer to the data and the length of the data. This function writes the string represented by aRange to the buffer as a Unicode string. NULL is not automatically added to the end. The buffer must be large enough.

(2) Coding conversion

C-style or byte-type strings and NSStrings can be converted to and from each other. String encoding is defined as the enumeration type NSStringEncoding.

– (id)initWithCString:(constchar*)nullTerminatedCString

encoding:(NSStringEncoding)encoding

// Initialize an NSString object with a C-style string, nullTerminatedCString requires nullTerminatedCString, encoding. Convenience constructor: stringWithCString: encoding

– (__strongconstchar*)cStringUsingEncoding:(NSStringEncoding)encoding// returns the c-style string of the message receiving object, the encoding specified by encoding. In memory management mode based on reference counting, the returned string is freed at the same time the message receiving object is freed. In memory management mode, garbage collection is not garbage collected because strong Pointers are returned.

– (id)initWithData:(NSData *)data

encoding:(NSStringEncoding)encoding

// Initialize NSString objects with binary data stored in data.

– (NSData *)dataUsingEncoding:(NSStringEncoding)encoding

// The contents of the NSString that receives the message are encoded in the method specified in Encoding, and the result is stored in an NSData object and returned.

– (BOOL) canBeConvertedToEncoding: (NSStringEncoding) encoding / / test receive messages nsstrings object can be converted to encoding encoding. Use the class method availableStringEncodings to return the encoding available in the current environment.

-(NSString*)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding

// Can replace some special characters, mainly used for URL strings, such as replacing Spaces with %20, etc. StringByReplacingPercentEscapesUsingEncoding: is the inverse transformation of the method.

(3) Generate a string of the specified format

%@ must be an object. When %@ is printed (for example, NSLog(@ “%@”, test)), it calls the description method of test and returns the result stored in %@. NSString does not support automatic conversion of parameter types, so ensure that the specified type is the same as the type of the parameter passed in.

– (id)initWithFormat:(NSString *)format ,… // Generates a string based on the format string specified in format, which is used to initialize the message receiver. Parameters in format are separated by commas, and format strings cannot be empty. Convenience constructor: stringWithFormat:

(4) Comparison of NSString

String comparison will return the value of an NSComparisonResult type, it is the enum data type, a total of three values, respectively NSOrderedAscending, NSOrderedSame, NSOrderedDescending.

– (NSComparisonResult)compare:(NSString *)aString// case sensitive comparison

– (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString

// Case insensitive comparison

– (NSComparisonResult)localizedStandardCompare:(NSString *)aString

// Compare according to the sorting rules of the Mac system Finder.

– (

BOOL

)isEqualToString:(NSString *)aString

– (

BOOL)hasPrefix:(NSString *)aString// checks whether the string starts with aString. You can also use the method commonPrefixWithString: options: to retrieve the same string as the beginning of the message receiver and the parameter string.

(5) Append content to string

– (NSString *)stringByAppendingString:(NSString *)aString

– (NSString *)stringByAppendingFormat:(NSString *)format

// Appends a format string to the receiver string, and returns a new string.

(6) Intercepting strings

Intercepts the specified string and returns. Use the structure NSRange to indicate the starting position and length of the string to intercept.

– (NSString *)substringToIndex:(NSUInteger)anIndex// returns a new string ranging from the first character of the receiver string to the end of anIndex, excluding anIndex

– (NSString *)substringFromIndex:(NSUInteger)anIndex

// Returns a new string from the beginning of anIndex to the end, including the characters at the position of anIndex.

– (NSString *)substringWithRange:(NSRange)aRange

// Returns the start position and length of the new string specified by aRange.

(7) Retrieval and replacement

– (NSRange) rangeOfString:(NSString *)aString// if aString is found, the position and length of aString are returned. If not found, return an NSRange object of type 0 with position NSNotFound.

– (NSRange)lineRangeForRange:(NSRange)aRange

// returns the range of the NSRange line.

– (NSString *)stringByReplacingCharactersInRange:(NSRange)aRange

withString:(NSString *)replacement

– (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target

withString:(NSString *)replacement

(8) Case processing

You can use the lowercaseString method to convert all uppercase letters in a string to lowercase, as opposed to uppercaseString. In addition to these two, the capitalizedString method capitalizes the first letter of all words and the rest of the letters.

(9) Numerical conversion

The doubleValue method converts an NSString to a value of type double. Similar and floatValue intValue integerValue, boolValue. The boolValue method returns YES when the input string begins with any letter of Y, Y,T, or T, or a number that does not start with 0.

(10) Path processing

The path to the file can be represented by NSString. Unix uses the slash as the path separator. The NSHomeDirectory () method returns the current user’s home directory. The file path @tmp /image/cat.tif is used as an example.

– (NSString *)lastPathComponent// Extracts the last component in the file path. The above example returns “cat.tiff”.

– (NSString *)stringByAppendingPath:(NSString *)aStr

// Appends aStr to the end of an existing string and returns it, automatically appending delimiters as needed.

– (NSString *)stringByDeletingLastPathComponent

// Remove the last component of the path. If the result returned is not the root path, the last path separator is also removed.

– (NSString *)pathExtension

// Returns the file extension without “. . Returns an empty string with no extension.

– (NSString *)stringByAppendingPathExtension:(NSString *)aString

/ / will “.” And specify the extension to add to the last component of the existing path.

– (NSString *)stringByDeletingPathExtension

// Delete file extensions including “. , returns the original string without the extension.

– (

BOOL isAbsolutePath// Checks whether the path is an absolute path and returns YES if so.

+ (NSString *)pathWithComponents:(NSArray *)components

// Use the elements in Components to build the path, adding the path separator “/” automatically when combined. To generate an absolute path, use @ / for the first element in the array. To end with a path separator, the last element of the array uses the empty string @ “”.

– (NSArray *)pathComponents

// Just the opposite of pathWithComponents.

– (NSString *)stringByExpandingTildeInPath

// If the first character of the path is a surrogate character (beginning with ~, for example: ~ /), the path string of the user’s home directory is returned. Otherwise, the input string is returned. StringByAbbreviatingWithTildeInPath function on the contrary, the standard format of the string is converted to use generation of character string.

– (

FileSystemRepresentation __strongconstchar *) / / C style of the path string, using the current coding system.

(11) File input and output

– (

id

)initWithContentsOfFile:(NSString *)path

encoding:(NSStringEncoding)enc

error:(NSError **)error

// Initialize an NSString by reading the contents of the file path, encoded as enC. Failure to read the file releases the caller and sets the verbose error message to error while returning nil. Convenience constructor: stringWithContentsOfFile: encoding: error:

– (

id

)initWithContentsOfFile:(NSString *)path

usedEncoding:(NSStringEncoding *)enc

error:(NSError **)error

// The difference is that this function automatically identifies the encoding of the file and returns it via enC. The encoding of a file is determined by the content and extended attributes of the file. Convenience constructor: stringWithContentsOfFile: usedEncoding: error:

– (

BOOL

)writeToFile:(NSString *)path

atomically:(

BOOL

)useAuxiliaryFile

encoding:(NSStringEncoding)enc

error:(NSError **)error

// Write the contents of the string to the file with path as the path, using enC specified encoding when writing, return YES if successful. When useAuxiliaryFile is set to YES, a new temporary file is created and the contents of the string are written to the temporary file. It then renames the temporary file to the file specified by path after the write succeeds. This method does not damage the original file if a write error occurs. If the value is NO, the string content is directly entered into the file specified by path. If the write fails, NO is returned along with the cause of the error written to error and returned to the function caller.

(12) Others

– (id)init// Initializes the receiver and returns an empty string. Usually used for NSMutableString initialization. Convenience constructor: string.

– (

Id)initWithString:(NSString *)aString// returns aString object whose content is a copy of aString. AString can also be an instance object of NSMutableString. Use this method to generate an immutable string object from a mutable string object. Convenience constructor: stringWithString:

– (NSString *)description

// Returns a string of the contents of the message receiver. NSString’s description method will just return self.

– (

Id)propertyList// Returns a list of properties for the message receiver.

– (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)sep

// Split the message receiver string with the characters in the set of characters specified by the sep argument as delimiters and return an array of strings generated after the split.

NSMutableString:

NSMutableString is a subclass of NSString, so you can use all the methods defined in NSString. Undefined methods in NSString are illustrated below:

(1) Generation and initialization of instance objects

– (id)initWithCapacity:(NSUInteger)capacity// initializes an NSMutableString object. Capacity specifies the size of the NSMutableString object to be initialized. NSMutableString objects automatically expand memory as the string changes, so capacity doesn’t need to be very precise. In addition to this method, you can use the INIT method of NSString or the class method of NSString string: to generate an empty NSMutableString object. Convenience constructor: stringWithCapacity:

(2) Append the string

– (void)appendString:(NSString *)aString// appends aString to the end of the message receiver.

– (

Void) appendFormat (nsstrings *) format,… // Appends the format string to the end of the message receiver.

(3) Insert delete replacement

– (void

)insertString:(NSString *)aString

atIndex:(NSUInteger)loc

// Insert the human string aString at the atlndex location of the message receiver.

– (

Void)deleteCharactersInRange:(NSRange) void)deleteCharactersInRange:(NSRange)

– (

Void)setString:(NSString *)aString// copies the string specified by aString and sets it to the contents of the message receiver.

– (

void

)replaceCharactersInRange:(NSRange)aRange

withString:(NSString *)aString

// Replace the contents of aRange with the contents of aString.

– (NSUInteger)replaceOccurrencesOfString:(NSString *)target

withString:(NSString *) replacement.

options:(NSStringCompareOptions)opts

range:(NSRange)searchRange

//searchRange if the string target exists in the range, it is replaced with replacement. The return value of this function is the number of substitutions. Use the opts option to ignore case, use regular expressions for substitution, and so on.

NSData

NSData:

NSData is a Cocoa wrapper for binary data that can be treated as objects.

NSData has the advantage of being more abstract than ARRAYS in C, making memory management easier, and is the standard for manipulating binary data in the cocoaAPI.

NSData is immutable, so instance objects cannot change their contents once they are created. If you want to change the content of the data, you need to use the class NSMutableData, which you’ll see later. Instance objects of NSData and NSMutableData are sometimes called data objects.

The interface file for NSData is defined in Foundation/ nsdata.h. NSData is implemented as a family of classes, so you can’t subclass NSData in the usual way. Here are some of the main methods of the NSData class. If you want to know all of them, please refer to apple’s documentation.

(1) Generation and initialization of data objects

– (id)initWithBytes:(constvoid*)bytes length:(NSUInteger)length// copy the data starting with bytes and length to the content of the data object and initialize it. Convenience constructor: dataWithBytes:length:

– (id)initWithBytesNoCopy:(void*)bytes length:(unsigned)length freeWhenDone:(BOOL)flag; // Initialize bytes with length as the content of the data object. The generated NSData stores Pointers to data and does not copy data. When flag is YES, the generated NSData object is the owner of bytes. Bytes are also freed when the NSDate object is freed, so bytes must be allocated on the heap via malloc. When flag is NO, bytes will not be released automatically. When releasing bytes, be careful not to release bytes while the NSData object is still in use. Convenience constructor: datawithBytesNoCopy: length: freeWhenDone:

– (id)initWithData:(NSData *)data// creates a new NSData object with the specified NSData object aData. The argument can be an NSMutableData object, so this method generates an immutable NSData object for a mutable NSMutableData object. Convenience constructor: dataWithData:

+ (id)data// Returns a temporary NSDate object of length 0. This method is mostly used in NSMutableData (creating an NSData of length 0 doesn’t make much sense). The corresponding initialization method is init.

(2) Access data in NSData

– (NSUInteger)length// Returns the length of the data in the NSData object

– (

Constvoid *)bytes// Returns the first pointer to the data in the NSData object

– (

Void)getBytes:(void*)buffer length:(NSUInteger)length// copy the data of the NSData object to the buffer. The copy starts from the beginning of the data in the NSData object. The length of the copy is length. To get data in a specified range, use the getBytes:range method.

– (NSData *)subdataWithRange:(NSRange)range

// Generate a new NSData object with data in the specified range and return it.

– (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange

// Returns the location and length of the dataToFind if the same data can be found within the range specified by the searchRange in the receiver. Mask is a search option that allows you to search from back to front. DataToFind cannot be considered nil.

(3) Comparison

– (BOOL)isEqualToData:(id)anObject// YES is returned if the length and content of two NSData are the same

(4) File input and output

You can initialize an NSData object by reading human data from a file, or output the contents of an NSData object to a file. In addition to functions that specify file paths using NSString, there are also functions that use NSURL to specify file paths.

An array of class

NSArray:

Arrays can hold objects of the same class and objects of different classes, but they can’t hold nil, which is used to mark the end of an array.

An NSArray is an immutable array. Once created, no elements can be added, removed, or modified.

Ownership of array objects:

Arrays, collections, and dictionary objects containers that can contain multiple objects are collectively called collections. An object receives a retain message when it is placed into the collection and a release message when it is removed from the collection.

Quick enumeration:

OC2.0 provides a syntax for traversing container classes called fast enumeration. for… In grammar.

Collections can be mutable or immutable, and mutable collections are not allowed to be changed during the loop. If the collection is changed, an exception is thrown.

The order in which elements are traversed depends on the type of container. If it is an array, it is traversed from the beginning, whereas if it is a collection or dictionary type, the order of traversal depends on the internal implementation of the container.

Variables can be defined in conditions for, in which case variables are defined only in conditions for… The in syntax block is valid.

Enumerator NSEnumerator:

An enumerator is an abstract class that iterates through element objects in a collection class. The enumerator does not have a public interface to create instances and cannot send alloc messages to the enumerator. While iterating through a collection object with an enumerator, adding or deleting objects to the collection object can lead to unexpected and dangerous results.

In reference counting mode, the enumerator object has ownership of the collection object as it traverses through the enumerator, and automatically relinquished ownership of the collection object when the last element is fetched. Also, because the enumerator is a temporary object, it will be released when its auto-release pool is released.

Fast enumerators and enumerators:

Neither fast enumerators nor enumerators can change an element in a collection during traversal. If you want to change a collection object during the loop, you can use subscripts to loop through it. If you want to delete an element in a collection, you need to traverse backwards.

Fast enumeration internal c language, fast speed.

for… The in syntax replaces “collection” after “in” with “enumerator”.

Collection classes:

It’s a collection of single-valued objects, and nssets are unordered, so you can only hold one object.

NSMutableSet has a subclass, NSCountedSet, which is a mutable collection class that counts the number of objects in the collection. This class can hold multiple objects with the same value.

The dictionary class

The data in the dictionary is stored as key-value pairs, one of which is called entry. Keys and values can be any object except nil, typically using strings as keys. Keys are keywords.

When a value consists of multiple strings, you can enclose them with (), in which case the dictionary object’s value is an array object.

The keys of a dictionary must be unique.

The value of a dictionary object can be NSNull to indicate that a dictionary object is empty.

When an object is used as a key or value in a dictionary, the dictionary stores a copy of that object.

NSDictionary:

Immutable, once created, can only be queried, cannot add, delete, or modify its content.

Wrapper class

The Collection classes of the Cocoa Foundation framework only store objects, not primitive types of data. So Cocoa provides NSNumber classes to wrap char, int, long, and so on. For complex data types like structures and Pointers, NSNumber doesn’t have a way to store them as objects, so you can use NSValue. NSValue is the parent of NSNumber, and NSValue can wrap any object as an object. NSNull is a wrapper class defined to put nil into a collection class.

Note that NSInteger is not an object, but a typedef of the basic data type.

NSValue:

The interface is defined in Foundation/nsvalue.h, and coordinates and other structures are defined in Foundation/NSGeometry.

Type encoding and @encode ()

OC data types, even custom types, can be represented using asciI-encoded type description strings. @encode () can return a type description string for a given data type. For example: @encode (int) returns “I”.

Here is an example of creating an NSValue instance for a structure:

struct

grid {

int

x, y;

double

weight;

};

structgridfoo, bar; id

obj;

// Encapsulates the structure foo and returns an object obj

obj = [[NSValue alloc] initWithBytes:&foo objCType:

@encode(struct

grid)];

// Read data from obj into variable bar

[obj getValue:&bar];

An NSValue can only wrap data of a certain length. For example, an NSValue cannot wrap a C-style string.

NSValue and NSNumber are implemented as clusters of classes, so they cannot be subclassed in the usual way.

NSNull

Nil can’t be put in arrays or dictionaries because nil has a special meaning in them, but sometimes we do need a special object to represent a null value.

NSURL

About the URL:

Uniform resource locator. In addition to being used on the Internet, it can also be used to represent native resources. In addition to HTTP, other protocols can also use urls to access resources.

Mac OS X and iOS specify four ways in which NSURL can be used to access resources:

HTTP: Hypertext link protocol

HTTPS: Secure version of HTTP, which is the combination of HYPERtext Transfer Protocol (HTTPS) and SSL/TLS

FTP: file transfer protocol

File: Accesses files on a host

Accessing a resource can be written as follows:

Protocol name: // Host name/path of resources on the host

Use specialized NSURL classes when manipulating urls, rather than parsing them manually as strings.

In the case of string as the return value, it must be a URL-encoded string. If the method name contains string, the argument passed in must also be encoded. Path, on the other hand, is used to represent the path to the URL and is returned as an encoded string, either as a return value or as a parameter.