標籤:
- (void)modernSyntax {/* 一、文法新特性NSNumber、NSArray、NSDictionary*/ // ---- NSNumber 新文法 ---- NSNumber *num = nil; // num = [NSNumber numberWithInt:1]; num = @1; // numberWithInt/numberWithShort num = @1u; // numberWithUnsignedInt/numberWithUnsignedShort num = @‘x‘; // numberWithChar/numberWithUnsignedChar num = @1l; // numberWithLong num = @1lu; // numberWithUnsignedLong num = @1ll; // numberWithLongLong num = @1llu; // numberWithUnsignedLong num = @1.1f; // numberWithFloat num = @1.234; // numberWithDouble num = @YES; // numberWithBool NSUInteger i = 1; num = @(i); //變數用新特性的時候用”()“包起來 //---- NSArray 新文法 ---- NSArray *array = nil; //array = [NSArray arrayWithObjects:@1, @2, @3, nil]; array = @[@1, @2, @3]; // 初始化(靜態變數不能用新特性,舊方法也不行)//static NSArray *aa = @[@1, @2]; id obj0 = array[0]; // 擷取子項目 // 遍曆方法1 NSUInteger count = array.count; for (NSUInteger i=0; i<count; i++) { NSLog(@"%@", array[i]);// } // 遍曆方法2 for (id obj in array) { NSLog(@"%@", obj); } // 遍曆方法3 [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if (*stop == NO) { NSLog(@"|idx:%@-obj:%@|", @(idx), obj); } }]; //---- NSDictionary 新文法 ---- NSDictionary *dic = nil; // dic = [NSDictionary dictionaryWithObjectsAndKeys:@0, @"key0", @1, @"key1", @2, @"key2", nil]; dic = @{@"key0":@0, @"key1":@1, @"key2":@2};// 初始化方法 id obj1 = dic[@"key0"];// 擷取 //遍曆 [dic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (*stop == NO) { NSLog(@"|key:%@-obj:%@|", key, obj); } }]; /* 二、synthesize*/ //寫了@property不用再寫@synthesize,Xcode自動合成}
iOS 文法新特性-modern syntax(iOS6後,Xcode4.4後,OS X 10.8.2後)