推荐用字面量语法
优点:(代码简洁且易读)
- (void)testNumberObj
{
//推荐用
NSNumber *intNumber = @1;
NSNumber *floatNumber = @2.3f;
NSNumber *doubleNumber = @4.56;
NSNumber *boolNumber = @YES;
NSNumber *charNumber = @'a';
//不推荐
NSNumber *nIntNumber = [NSNumber numberWithInt:1];
//....等
}
- (void)testNSStringObj
{
//推荐用
NSString *tmpStr = @"多用字面量语法";
//不推荐
NSString *nTmpStr = [NSString stringWithFormat:@"少
用字面量语法的等效方法"];
}
- (void)testNSArrayObj
{
//推荐用
NSArray *familyMemberArr = @[@"father",@"mother",@"brother",@"sister"];
NSString *brotherStr = familyMemberArr[2];
//不推荐
NSArray *nFamilyMemberArr = [NSArray arrayWithObjects:@"father",@"mother",@"brother",@"sister", nil];
NSString *nBrotherStr = [familyMemberArr objectAtIndex:2];
}
- (void)testDictonaryObj
{
//推荐用
NSDictionary *tmpDataDic = @{@"id":@100018,
@"data":@"className"};
NSString *idStr = tmpDataDic[@"id"];
//不推荐
NSDictionary *nTmpDataDic = [NSDictionary dictionaryWithObjectsAndKeys:
@"id",@100018,
@"data",@"className", nil];
NSString *nIdStr = [tmpDataDic objectForKey:@"id"];
}
注意事项(局限):
1.数组和字典用字面量,要保证对象值不为nil,否则会奔溃。
2.字面量创建出来的对象默认是不可变的,如果要创建可变的对象,用如下方式
//可变
NSMutableArray *mutableArr = [@[@"father",@"mother",@"brother",@"sister"]mutableCopy];
如果你发现本文对你有所帮助,如果你认为其他人也可能受益,请把它分享出去。