您的位置:首页 > 移动开发 > IOS开发

ios developer tiny share-20161013

2016-10-20 18:40 218 查看
今天讲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 a
format 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 the

String Programming Guide.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息