●概要NSStringクラスは不変文字列を管理するオブジェクトのプログラムインターフェイスを宣言します。(不変文字列は、生成した後で変更できないテキスト文字列として定義されます。NSStringは、Unicode文字の配列すなわちテキスト文字列として表されて実装されます。)NSStringの可変サブクラスはNSMutableStringです。NSStringクラスは、lengthとcharacterAtIndex:の2つのプリミティブメソッドを持ち、インターフェイスの他の全...
seen from China

seen from Malaysia
seen from United States
seen from Germany
seen from United States

seen from Malaysia

seen from United States

seen from T1
seen from United States
seen from Malaysia

seen from Malaysia
seen from T1
seen from Türkiye
seen from United Kingdom
seen from Kuwait
seen from China
seen from Slovakia

seen from Germany
seen from Brazil
seen from United Kingdom
●概要NSStringクラスは不変文字列を管理するオブジェクトのプログラムインターフェイスを宣言します。(不変文字列は、生成した後で変更できないテキスト文字列として定義されます。NSStringは、Unicode文字の配列すなわちテキスト文字列として表されて実装されます。)NSStringの可変サブクラスはNSMutableStringです。NSStringクラスは、lengthとcharacterAtIndex:の2つのプリミティブメソッドを持ち、インターフェイスの他の全...

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
String or NSString, which one ought to be
Use native types whenever possible
In general, you should use the Swift native types as possible as you can because they are optimized to compile for better performance. But wait, I just said unavoidable, right? Let's take a look at an Objective-C based class NSRegularExpression as an example.
let str = "Hello, playground" do { let expression = try NSRegularExpression(pattern: "\\s{1,}", options: [.anchorsMatchLines]) let range = NSRange(location: 0, length: str.characters.count) let matches = expression.matches(in: str, options: [], range: range) for match in matches { print(match) } } catch { print(error.localizedDescription) }
In above snippet, we can see the function func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult] which only accepts NSRange variable as a parameter; therefore, translating Range type str.startIndex..<str.endIndex to NSRange class will be undoubtedly necessary once we have our codes interoperate and be mixed up String, NSString, Range and NSRange. However, an experienced Swift programmer might find there is a lethal flaw in above snippet also. It's about the way of calculating string length, str.characters.count. The practice like this is highly error prone because Swift uses Extended Grapheme Clusters. Ex, a Unicode smiley symbol. Swift sees it as one character, but the NSString method sees it as two.
So... is there a principal or suggestion?
If we don't want to pay too much attention to the difference like above example, for risk-free, my suggestion is always to cast String to NSString once facing Objective-C based function, like NSRegularExpression. Of course, the strategy will not be necessary until native Swift function is introduced, ex. we might see RegularExpression someday. So, in order to fix above flaw. The way to calculate length should be like the snippet below. All in all, there are always native ways to deal with variables; however, a risk-free or less error prone strategy can save us a day sometimes :)
// Option 1: Cast String to NSString let range = NSRange(location: 0, length: (str as NSString).length) // Option 2: Calculate utf16 count when accessing on a Swift String value. let range = NSRange(location: 0, length: str.utf16.count)
A tip to extract substring intuitively for Swift
A tip to extract substring intuitively for Swift
With Objective-C, the function func substring(from: Int) -> String is very easy to be implemented because of Int parameter is very intuitive to be taken by human natural. However, the story is very different for Swift side because default inferred string type is String and it only takes String.Index as its parameter.
Xamarin - iOS - tired of new NSString(yourstring)?
Use this:
public static class NSHelper { public static NSString ToNSString(this string toNSString) { return new NSString(toNSString); } }
and enjoy yourstring.ToNSString();
Blogs posted in iPhone. The title is How to convert NSData to NSString or vice versa in Objective C and Swift - Find Nerd
Convert NSData to NSString or vice versa in ObjectiveC and Swift.

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
NSString is the crown jewel of Foundation. But as powerful as it is, one would be remiss not to mention its toll-free bridged cousin, CFMutableString—or more specifically, CFStringTransform.
Literal syntax
Các class NSString, NSArray, NSNumber, NSDictionary thuộc Foundation framework. Chúng có cú pháp dài dòng giống như đặc trưng của ngôn ngữ Objective-C. Tuy nhiên, từ Objective-C 1.0 đã xuất hiện literal syntax giúp việc viết code ngắn gọn và dễ đọc hơn.
Literal NSString
Không dùng literal syntax:
NSString *someString = [NSString stringWithFormat:@"some String"];
Literal syntax:
NSString *literalString = @"literal String";
Literal NSNumber
Không dùng literal syntax:
NSNumber *someNumber = [NSNumber numberWithInt:1];
Literal syntax:
NSNumber *literalNumber = @1;
Không chỉ với kiểu dữ liệu int, literal syntax còn dùng với tất cả các kiểu khác mà NSNumber có thể đại diện.
NSNumber *intNumber = @1; NSNumber *floatNumber = @1.0f; NSNumber *doubleNumber = @3.14217; NSNumber *boolNumber = @YES; NSNumber *charNumber = @'a';
Literal syntax còn dùng được với một expression:
int x = 2; int y = 3.14; NSNumber *expressionNumber = @(x * y);
Literal NSArray
Không dùng Literal syntax:
NSArray *animals = [NSArray arrayWithObjects:@"cats", @"dog", @"mouse", @"bird", nil];
Literal syntax:
NSArray *animals = @[@"cats", @"dog", @"mouse", @"bird"];
Không chỉ khởi tạo array, việc lấy ra phần tử của NSArray với literal syntax (subscripting) cũng ngắn gọn hơn:
Không dùng Literal syntax:
NSString *dog = [animals objectAtIndex:1]
Dùng literal syntax:
NSString *dog = animals[1];
Lưu ý, khi tạo NSArray bằng cách sử dụng literal syntax, nếu một phần tử bằng nil, một exception như sau sẽ bị xổ ra:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[1]'
Điều này dẫn đến một vấn đề nhỏ khi sử dụng literal syntax. Ví dụ:
NSString *string1 = @"string1"; NSString *string2 = nil; NSString *string3 = @"string3"; NSArray *arrayA = [NSArray arrayWithObjects:string1, string2, string3, nil]; NSArray *arrayB = @[string1,string2,string3];
Trong trường hợp này, arrayB sẽ khiến exception bị xổ ra do có phần từ nil trong mảng, arrayA vẫn sẽ được tạo và sẽ chỉ có một phần tử là string1 do hàm mà arrayA dùng để khởi tạo sẽ dừng khi nó bắt gặp nil nhưng do string2 là nil nên nó dừng sớm hơn dự kiến ban đầu.
Sự khác nhau ở trên có nghĩa là literal syntax an toàn hơn trong việc khởi tạo mảng do nó bắn ra exception khi có phần tử nil trong mảng còn hơn là việc tạo ra mảng mà có ít phần tử hơn dự kiến. Exception được bắn ra sẽ giúp tìm ra lỗi dễ dàng hơn.
Literal NSDictionary
Không dùng literal syntax:
NSDictionary *personData = [NSDictionary dictionaryWithObjectsAndKeys: @"Tuan Hai", @"firstName", @"Tran", @"lastName", [NSNumber numberWithInt:24], @"age", nil];
Nhìn khá loạn, do thứ tự value-key của cách này. Sử dụng literal syntax:
NSDictionary *personData = @{@"firstName" : @"Tuan Hai", @"lastName" : @"Tran", @"age" : @24};
Rõ ràng, dùng literal syntax ngắn gọn hơn và cũng giống với cách ta thường nghĩ về NSDictionary đó là key-value. Tương tự NSArray, NSDictionary cũng xổ ra exception khi có phần tử nil trong lúc khởi tạo bằng literal syntax.
Cũng giống như NSArray, NSDictionary có thể được truy cập bằng literal syntax. Cách cũ:
NSString *firstName = [personData objectForKey:@"firstName"];
Literal syntax:
NSString *firstName = personData[@"firstName"];
NSMutableArray và NSMutableDictionary
Giống cách truy cập các phần tử bằng index trong NSArray hay key trong NSDictionary, ta có thể set giá trị của nó nếu object là mutable. Cách cũ:
[mutableArray replaceObjectAtIndex:1 withObject:@"dog"]; [mutableDictionary setObject: @"Tuan Hai" forKey:@"firstName"];
Literal syntax:
mutableArray[1] = @"dog" mutableDictionary[@"firstName"] = @"Tuan Hai";
Hạn chế
Khi tạo một mutable object bằng literal syntax, cần phải gọi thêm hàm mutableCopy:
NSMutableArray *mutableArray = [@[@1, @2, @3] mutableCopy];
Tuy phải gọi thêm một lời gọi hàm nhưng lợi ích của việc dùng literal syntax lớn hơn hạn chế này.
Ghi nhớ
Sử dụng literal syntax để khởi tạo string, array, number, dictionary vì cú pháp ngắn gọn, rõ ràng.
Truy cập phần tử của array và dictionary bằng subscript
Đảm bảo không có phần tử nil được thêm vào array và dictionary khi sử dụng literal syntax.