190

我正在浏览 Xcode 4.4 的发行说明并注意到这一点:

LLVM 4.0 编译器

Xcode 现在包含 Apple LLVM 编译器 4.0 版,包括以下新的Objective-C 语言功能: [...]
- Objective-C 文字:为 NSArray、NSDictionary 和 NSNumber 创建文字,与 NSString 的文字相同

我对这个功能很感兴趣。我并不完全清楚文字是如何NSString工作的,以及如何在NSArrayNSDictionary和. 上使用它们NSNumber

详情是什么?

4

4 回答 4

395

从http://cocoaheads.tumblr.com/post/17757846453/objective-c-literals-for-nsdictionary-nsarray-and逐字复制:

Objective-C 文字:现在可以为 NSArray、NSDictionary 和 NSNumber 创建文字(就像可以为 NSString 创建文字一样)

NSArray 字面量

之前:

array = [NSArray arrayWithObjects:a, b, c, nil];

现在:

array = @[ a, b, c ];

NSDictionary 字面量

之前:

dict = [NSDictionary dictionaryWithObjects:@[o1, o2, o3]
                                   forKeys:@[k1, k2, k3]];

现在:

dict = @{ k1 : o1, k2 : o2, k3 : o3 };

NSNumber 字面量

之前:

NSNumber *number;
number = [NSNumber numberWithChar:'X'];
number = [NSNumber numberWithInt:12345];
number = [NSNumber numberWithUnsignedLong:12345ul];
number = [NSNumber numberWithLongLong:12345ll];
number = [NSNumber numberWithFloat:123.45f];
number = [NSNumber numberWithDouble:123.45];
number = [NSNumber numberWithBool:YES];

现在:

NSNumber *number;
number = @'X';
number = @12345;
number = @12345ul;
number = @12345ll;
number = @123.45f;
number = @123.45;
number = @YES;

[编辑]

http://news.ycombinator.com/item?id=3672744上的zxoq添加了更多有趣的新下标。(添加文字):

arr[1]      === [arr objectAtIndex:1]
dict[@"key"] === [dict objectForKey:@"key"]

[编辑 2]

新的 ObjC 文字在多个WWDC 2012会议中进行了讨论。我故意没有删除每张幻灯片的文件名和时间,所以如果你愿意,你可以自己找到它们。它们本质上与本文中所述相同,但还有一些我将在图片上方提到的新事物。

请注意,图像都很大。只需将它们拖到另一个选项卡中即可以原始大小查看它们

文字与拳击

[NSNumber numberWithint:42]
[NSNumber numberWithDouble:10.8]
[NSNumber numberWithBool:YES]
[NSNumber numberWithint:6 + x * 2012]

文字与拳击

@42
@10.8
@YES
@(6 + x * 2012)

集合下标

[NSArray arrayWithObjects: a, b, c, nil]
[array objectAtIndex:i]
[NSDictionary dictionaryWithObjectsAndKeys: v1, k1, v2, k2, nil];
[dictionary valueForKey:k]

集合下标

@[a, b, c]
array[i]
@{k1:v1, k2:v2}
dictionary[k]

@# 数字,@{} 字典,@


这部分是新的。表达式文字

当你有一个表达式(M_PI / 16例如)时,你应该把它放在括号内。

此语法适用于数字表达式、布尔值、在 (C-) 字符串中查找索引、布尔值、枚举常量,甚至字符串!

表达式文字

NSNumber *piOverSixteen = [NSNumber numberWithDouble: (M_PI / 16)];

NSNumber *hexDigit = [NSNumber numberWithChar:"0123456789ABCDEF"[i % 16]];

NSNumber *usesScreenFonts = [NSNumber numberWithBool:[NSLayoutManager usesScreenFonts]];

NSNumber *writingDirection = [NSNumber numberWithInt:NSWritingDirectionLeftToRight];

NSNumber *path = [NSString stringWithUTF8String: getenv("PATH")];

表达式文字

NSNumber *piOverSixteen = @( M_PI / 16 );

NSNumber *hexDigit = @( "0123456789ABCDEF"[i % 16] );

NSNumber *usesScreenFonts = @( [NSLayoutManager usesScreenFonts] );

NSNumber *writingDirection = @( NSWritingDirectionLeftToRight );

NSNumber *path = @( getenv("PATH") );

有关字符串以及如何/何时可以使用此文字语法的更多信息:

盒装字符串表达式

NSString *path = [NSString stringWithUTF8String: getenv("PATH")];
for (NSString *dir in [path componentsSeparatedByString: @":"]) {
    // search for a file in dir...
}

盒装字符串表达式

NSString *path = @( getenv("PATH") );
for (NSString *dir in [path componentsSeparatedByString: @":"]) {
    // search for a file in dir...
}

数组字面量如何工作

数组字面量如何工作

// when you write this:
array = @[a, b, c ];

// compiler generates:
id objects[] = { a, b, c };
NSUInteger count = sizeof(objects) / sizeof(id);
array = [NSArray arrayWithObjects:objects count:count];

字典文字如何工作

字典文字如何工作

// when you write this:
dict = @{k1 : o1, k2 : o2, k3 : o3 };

// compiler generates:
id objects[] = { o1, o2, o3 };
id keys[] = { k1, k2, k3 };
NSUInteger count = sizeof(objects) / sizeof(id);
dict = [NSDictionary dictionaryWithObjects:objects
                                   forKeys:keys
                                     count:count];

更多关于数组下标

数组下标

@implementation SongList {
    NSMutableArray *_songs;
}

- (Song *)replaceSong:(Song *)newSong atindex:(NSUinteger)idx {
    Song *oldSong = [_songs objectAtIndex:idx];
    [_songs replaceObjectAtindex:idx withObject:newSong];
    return oldSong;
}

数组下标

@implementation SongList {
    NSMutableArray *_songs;
}

- (Song *)replaceSong:(Song *)newSong atindex:(NSUinteger)idx {
    Song *oldSong = _songs[idx];
    _songs[idx] = newSong;
    return oldSong;
}    

更多关于字典下标

字典下标

@implementation Database {
    NSMutableDictionary *_storage;
}

- (id)replaceObject:(id)newObject forKey:(id <NSCopying>)key {
    id oldObject = [_storage objectForKey:key];
    [_storage setObject:object forKey:key];
    return oldObject;
}

字典下标

@implementation Database {
    NSMutableDictionary *_storage;
}

- (id)replaceObject:(id)newObject forKey:(id <NSCopying>)key {
    id oldObject = _storage[key];
    _storage[key] = newObject;
    return oldObject;
}

[编辑 3]

Mike Ash有一篇关于这些新文字的精彩文章。如果您想了解更多有关这些内容的信息,请务必查看


于 2012-02-19T14:20:28.893 回答
15

Objective-C 编译器对类实例的内存布局有硬编码的知识NSConstantString,也就是__CFConstantString类。查看clang 源代码中的RewriteObjCStringLiteral函数。lib/Rewrite/RewriteModernObjC.cpp编译器只是发出与NSConstantString类实例布局匹配的数据。

NSArray文字和NSDictionary实例有几种可能性。他们可以做一些类似于他们对文字字符串所做的事情——在编译器中硬编码实例布局(对于一个特殊的子类)并在该布局中发出数据。或者他们可以让编译器发出仅在运行时创建实例的代码。

于 2012-02-19T08:48:22.813 回答
1
于 2012-11-12T17:13:05.843 回答
0

Apple LLVM Compiler 4.0 添加了对 Objective-C 的文字支持。它从at sign @

NSNumber 字面量

NSNumber *someBool = [NSNumber numberWithBool:YES];
//BOOL literal
NSNumber *someBool = @YES;
     
NSNumber *someChar= [NSNumber numberWithChar:'a'];
//character literal
NSNumber *someChar = @'a';
     
NSNumber *someInt = [NSNumber numberWithInt:1];
NSNumber *someInt = [NSNumber numberWithUnsignedInt:1U];
NSNumber *someInt = [NSNumber numberWithLong:1L];
NSNumber *someInt = [NSNumber numberWithLongLong:1LL];
//integer literal
NSNumber *someInt = @1;
NSNumber *someInt = @1U;
NSNumber *someInt = @1L;
NSNumber *someInt = @1LL;
     
NSNumber *someFloat = [NSNumber numberWithFloat:3.141592654F];
NSNumber *someFloat = [NSNumber numberWithDouble:3.1415926535];
//float literal
NSNumber *someFloat = @3.141592654F;    
NSNumber *someFloat = @3.1415926535; 

集合文字

NSArray *someArray = [NSArray arrayWithObjects: @"A", @"B", @"C", nil];
//array literal
NSArray *someArray = @[ @"A", @"B", @"C" ];

NSDictionary *someDict = [NSDictionary dictionaryWithObjectsAndKeys:
                           @"key1", @"value1",
                           @"key1", @"value2",
                           nil];
//dictionary literal
NSDictionary *someDict = @{ @"Character" : @"Zelda",
                         @"key1" : @"value2",
                         @"key2" : @value2 };

集合下标

NSString *var1 = [someArray objectAtIndex:0]; // Returns 'A' 
NSString *var2 = [someDict objectForKey:@"key1"]; // Returns 'value1'
//Collection Subscripting
//read
NSString *var1 = someArray[0]; // Returns 'A'
NSString *var2 = someDict[@"key1"]; // Returns 'value1'
//write to mutable collection
someArray[0] = @"AA";
someDict[@"key1"] = @"value11";

Boxed Expressions - 转换为 Objective-C 的 C 样式表达式。适用于数字、枚举、结构

//Syntax @( <expression> )
[NSNumber numberWithInt:(INT_MAX + 1)];
//Boxed Expressions
NSNumber *var = @(INT_MAX + 1); 
于 2021-02-19T12:40:05.173 回答