字面量声明方式 Objective-C Literal Value

版权声明:本文为博主原创文章,未经博主允许不得转载。 最近才注意到NSArray,NSDictionary,NSNumber有一种字面量方式声明。瞬间感觉写代码又省了好多事情。

只是百度了一下,从Xcode4.4就已经存在这种方式了,但是自己居然一直在使用Previously那些方法。

于是现在在这里做一次整理,方便自己记忆(其实是当初说要写博客,但是好久没写了,来补个数量尴尬)

借鉴:http://cocoaheads.tumblr.com/post/17757846453/objective-c-literals-for-nsdictionary-nsarray

也看了一下官方文档,但是上面那个链接给的非常详细。大家如果有愿意看的话,看上面那个地址就可以了,以下,只是为了自己学习。

Objective-C literals: one can now create literals for NSArray, NSDictionary, and NSNumber (just like one can create literals for NSString)

String Value

string_value ::= “text” | ’text'

NSArray:

Previously:

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

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

Now: array = @[ a, b, c ];

NSDictionary:

Previously:

NSDictionary *dict;

dict = [[NSDictionary alloc] initWithObjectsAndKeys:@[ o1, o2, o3 ],@[ k1, k2, k3 ], nil ];

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

Now:

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

NSNumber:

Previously:

NSNumber * number;

number = [NSNumber numberWithInt:12345];

//同理,这种初始化还有Char,Long,Float,Double,Bool等类型,不再一一列举

Now:

NSNumber *number;

number = @‘X’;

number = @12345;

number = @12345ul;

number = @12345ll;

number = @123.45f;

number = @123.45;

number = @YES;

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy