Objective-C中的NSNumber和NSString

In this tutorial we’ll discuss NSNumber and NSString data types used in Objective-C. The Foundation Framework defines several classes that provide the standard, object-oriented data structures found in other high level languages

在本教程中,我们将讨论在Objective-C中使用的NSNumberNSString数据类型。 Foundation Framework定义了几个类,这些类提供其他高级语言中提供的标准的,面向对象的数据结构

NS编号 (NSNumber)

We can’t use primitive data types like int and float directly in Foundation classes. For that NSNumber is used as an object wrapper for these primitives. It’s main job is to store and retrieve primitive values to and from the box. The NSNumber version of BOOL’s, char’s, int’s and double’s can all be created by simply prefixing the corresponding primitive type with the @ symbol; however, unsigned int’s, long’s, and float’s must be appended with the U, L, or F modifiers, as shown below.

我们不能在Foundation类中直接使用int和float之类的原始数据类型。 为此,将NSNumber用作这些原语的对象包装。 它的主要工作是在框中存储原始值并从中检索原始值。 只需使用@符号为相应的原始类型添​​加前缀,即可创建BOOLcharintdouble的NSNumber版本。 但是,必须在U,L或F修饰符后附加unsigned intlongfloat ,如下所示。

NSNumber *aBool = @NO;
NSNumber *aChar = @'z';
NSNumber *anInt = @2147483647;
NSNumber *aUInt = @4294967295U;
NSNumber *aLong = @9223372036854775807L;
NSNumber *aFloat = @26.99F;
NSNumber *aDouble = @26.99;

It’s possible to box arbitrary C expressions using the @() syntax hence allowing us to convert basic arithmetic calculations in NSNumber objects as shown below :

可以使用@()语法对任意C表达式进行装箱,从而使我们可以在NSNumber对象中转换基本的算术运算,如下所示:

double x = 24.0;
NSNumber *result = @(x * .15);
NSLog(@"%.2f", [result doubleValue]);

In the above code doubleValue is a dedicated method to return the primitive datatype from the NSNumber type.

在上面的代码中, doubleValue是一种专用方法,用于从NSNumber类型返回原始数据类型。

It’s not possible to change its associated value of NSNumber after we create it. They are immutable. In this sense, an NSNumber instance acts exactly like a primitive value. When we need a new double value, we create a new literal and don’t change an existing one.

创建NSNumber后,无法更改其关联值NSNumber。 他们是一成不变的 。 从这个意义上讲,NSNumber实例的行为完全类似于原始值。 当我们需要一个新的double值时,我们将创建一个新的文字,而不更改现有的文字。

比较数字 (Comparing Numbers)

In general, Objective-C has two types of comparison methods :

通常,Objective-C有两种类型的比较方法:

  • Pointer comparison uses the == operator to see if two pointers refer to the same memory address (i.e., the same object). It’s not possible for different objects to compare equal with this kind of comparison

    指针比较使用==运算符查看两个指针是否引用相同的内存地址(即,相同的对象)。 这种比较不可能使不同的对象相等
  • Value comparison uses methods like isEqualToNumber: to see if two objects represent the same value. It is possible for different objects to compare equal with this kind of comparison

    值比较使用isEqualToNumber:类的方法来查看两个对象是否表示相同的值。 这种比较可能使不同的对象相等

The below snippet shows one such example to compare two NSNumbers :

下面的代码片段显示了一个比较两个NSNumber的示例:

NSNumber *anInt = @27;
NSNumber *sameInt = @27U;
// Pointer comparison (fails)
if (anInt == sameInt) {
    NSLog(@"They are the same object");
}
// Value comparison (succeeds)
if ([anInt isEqualToNumber:sameInt]) {
    NSLog(@"They are the same value");
}

isEqualToNumber: guarantees that two values will compare equal, even if they are stored in different objects.

isEqualToNumber:即使两个值存储在不同的对象中,也可以保证两个值比较相等。

NSString (NSString)

Like NSNumber, NSString is also immutable type. It’s used to represent text in Objective-C. NSString provides built-in support for Unicode, which means that we can include UTF-8 characters directly in string literals.
The most basic way in which NSString object is represented is shown below :

像NSNumber一样,NSString也是不可变的类型。 它用于表示Objective-C中的文本。 NSString提供了对Unicode的内置支持,这意味着我们可以直接在字符串文字中包含UTF-8字符。
NSString对象的最基本表示方式如下所示:

NSString *sample = @"iOS Tutorials";

stringWithFormat: class method is useful for generating strings that are composed of variable values. It takes the same kind of format string as NSLog(). Try the following snippet in a new empty project!

stringWithFormat:类方法对于生成由变量值组成的字符串很有用。 它采用与NSLog()相同类型的格式字符串。 在一个新的空项目中尝试以下代码段!

NSString *message = [NSString stringWithFormat:@"That's a %@ %@ from %d!",
                     make, model, year];
NSLog(@"%@", message);

比较字符串 (Comparing Strings)

String comparisons are similar to NSNumber Comparison except the fact that isEqualToString: method is used. For partial comparisons hasPrefix: and hasSuffix: are used.

字符串比较类似于NSNumber比较,只是使用了isEqualToString:方法。 对于部分比较,使用hasPrefix:hasSuffix:

NSString *name = @"Programming Language";
if ([name isEqualToString:@"Programming Language"]) {
    NSLog(@"The name string holds the text Programming Language");
}
if ([name hasPrefix:@"Programming"]) {
    NSLog(@"The first name of the word is Programming");
}
if ([name hasSuffix:@"Language"]) {
    NSLog(@"The second name of the word is Language");
}

A compare: method is used for alphabetically sorting strings as shown in the example below:

compare:方法用于按字母顺序对字符串进行排序,如下例所示:

NSString *otherName = @"Objective-C";
NSComparisonResult result = [name compare:otherName];
if (result == NSOrderedAscending) {
    NSLog(@"The letter 'P' comes before 'O'");
} else if (result == NSOrderedSame) {
    NSLog(@"We're comparing the same string");
} else if (result == NSOrderedDescending) {
    NSLog(@"The letter 'P' comes after 'O'");
}

In the above snippet we’ve displayed the three types of return values and their description as shown below :

在以上代码段中,我们显示了三种类型的返回值及其说明,如下所示:

  • NSOrderedAscending : receiver < argument

    NSOrderedAscending :接收器<参数
  • NSOrderedSame : receiver == argument

    NSOrderedSame :接收者==参数
  • NSOrderedDescending : receiver > argument

    NSOrderedDescending :接收者>参数

组合字符串 (Combining Strings)

NSString *first = @"First Name";
NSString *second = @"Second Name";
NSString *result = [first stringByAppendingString:second];
NSLog(@"%@", result);        // First NameSecond Name
result = [first stringByAppendingFormat:@" %@", second];
NSLog(@"%@", result);        // First Name Second Name (note the space)

搜索字符串 (Searching Strings)

NSString’s search methods return an NSRange struct, which consists of a location and a length field. The location is the index of the beginning of the match, and the length is the number of characters in the match. If no match is found, location will contain NSNotFound.

NSString的搜索方法返回一个NSRange结构,该结构由一个位置和一个长度字段组成。 位置是比赛开始的索引,长度是比赛中的字符数。 如果找不到匹配项,则location将包含NSNotFound

NSString *text = @"Maserati GranCabrio";
NSRange searchResult = ;
if (searchResult.location == NSNotFound) {
    NSLog(@"Search string was not found");
} else {
    NSLog(@"'Cabrio' starts at index %lu and is %lu characters long",
          searchResult.location,        // 13
          searchResult.length);         // 6
}

We’ve used a random string in the above example and the starting index and the length of the substring matched is printed in the NSLog.(We’ve shown that result in the comments. You can try the example in an XCode Project.

在上面的示例中,我们使用了随机字符串,并且在NSLog中打印了起始索引和匹配的子字符串的长度。(我们在注释中显示了结果。您可以在XCode Project中尝试该示例。

NSMutableStrings (NSMutableStrings)

The NSMutableString class is a mutable version of NSString. Unlike immutable strings, it’s possible to alter individual characters of a mutable string without creating a new object. The methods discussed above are applicable in NSMutableString too. Although some methods such as stringByAppendingString: will still return a NSString object—not an NSMutableString.

NSMutableString类是NSString的可变版本。 与不可变字符串不同,可以更改可变字符串的各个字符而无需创建新对象。 上面讨论的方法也适用于NSMutableString。 尽管某些方法(例如stringByAppendingString:仍将返回NSString对象,而不是NSMutableString。

创建可变字符串 (Creating Mutable Strings)

stringWithString is used to create a NSMutableString from a literal or an existing NSString object.

stringWithString用于从文字或现有的NSString对象创建NSMutableString。

NSMutableString *result = [NSMutableString stringWithString:@"Mutable String Text"];

The setString: method lets us assign a new value to the instance as follows :

setString:方法使我们可以为实例分配一个新值,如下所示:

[result setString:@"Modified String"];

This brings an end to this tutorial. Our aim was to give a brief overview of NSNumber and NSString Data Types. There are plenty of methods that we’ll discuss is the series of iOS Tutorials.

本教程到此结束。 我们的目的是简要概述NSNumber和NSString数据类型。 我们将讨论iOS教程系列中的许多方法。

翻译自: https://www.journaldev.com/10128/nsnumber-and-nsstring-in-objective-c

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值