ios developer tiny share-20161013

来源:互联网 发布:网络大电影没办法发行 编辑:程序博客网 时间:2024/04/30 02:15

今天讲Objective-C的基本类型对应的对象封装类型


Objects Can Represent Primitive Values

If you need to represent a scalar value as an object, such as when working with the collection classes described in the next section, you can use one of the basic value classes provided by Cocoa and Cocoa Touch.

Strings Are Represented by Instances of the NSString Class
As you’ve seen in the previous chapters, NSString is used to represent a string of characters, like Hello World. There are various ways to create NSString objects, including standard allocation and initialization, class factory methods or literal syntax:

NSString *firstString = [[NSString alloc] initWithCString:"Hello World!" encoding:NSUTF8StringEncoding];NSString *secondString = [NSString stringWithCString:"Hello World!"encoding:NSUTF8StringEncoding];NSString *thirdString = @"Hello World!";

Each of these examples effectively accomplishes the same thing—creating a string object that represents the provided characters.

The basic NSString class is immutable, which means its contents are set at creation and cannot later be changed. If you need to represent a different string, you must create a new string object, like this:

NSString *name = @"John";name = [name stringByAppendingString:@"ny"];    // returns a new string object

The NSMutableString class is the mutable subclass of NSString, and allows you to change its character contents at runtime using methods like appendString: or appendFormat:, like this:

NSMutableString *name = [NSMutableString stringWithString:@"John"];[name appendString:@"ny"];   // same object, but now represents "Johnny"



Format Strings Are Used to Build Strings from Other Objects or Values

If you need to build a string containing variable values, you need to work with aformat string. This allows you to use format specifiers to indicate how the values are inserted:

int magicNumber = ...NSString *magicString = [NSString stringWithFormat:@"The magic number is %i", magicNumber];

The available format specifiers are described in String Format Specifiers. For more information about strings in general, see theString Programming Guide.

0 0
原创粉丝点击