字面量文法的使用--IOS

來源:互聯網
上載者:User

標籤:字面量   字典   數組   

使用oc時,經常會用到NSString,NSNumber,NSArray,NSDictionary,下面是關於他們的字面量文法的使用。

(1)字面數值

   有時需要把整數,浮點數,布爾值封入oc對象中

      一般寫法:

    NSNumber *num = [NSNumber numberWithInt:1];

    使用字面量文法:

    NSNumber *num = @1;

   其他類型使用字面量文法:

   NSNumber *[email protected];

   NSNumber *[email protected];

   NSNumber *[email protected];

   NSNumber *[email protected];

   NSNumber *[email protected]‘a‘;

   字面量也適用於以下運算式:

   int x=5;

   float y =6.15f;

   NSNumber *[email protected](x*y);

   (2)字面量數組

   一般寫法:

   NSArray *animals=[NSArray arrayWithObject:@"cat",@"dog",@"mouse",nil];

   使用字面量文法:

   NSArray *[email protected][@"cat",@"dog",@"mouse"];

   數組的操作

   一般寫法:

   NSString *dog=[animals objectAtIndex:1];

   使用字面量:

   NSString *dog=animals[1];

   (3)字面量字典

   一般寫法:

  NSDictionary *personData=[NSDictionarydictionaryWithObjectsAndKeys:@"Matt",@"firstName",@"Galloway",@"lastName",[NSNumber numberWithInt:28],@"age",nil];

  使用字面量:

  NSDictionary *[email protected]{@"firstName":@"Matt",@"lastName":@"Galloway",@"age":@28};

  字典的操作

  一般寫法:

  NSString *lastName=[personData objectForKey:@"lastName"];

  使用字面量:

  NSString *lastName=personData[@"lastName"];

(4)可變數組與字典

  通過取下標操作,可以訪問數組中某個下標或字典中某個鍵所對應的元素。如果數組與字典對象是可變的,那麼也能通過下標修改其中的元素值。

 一般寫法:

[mutableArray replaceObjectAtIndex:1 withObject:@"dog"];

[mutableDictionary setObject:@"Galloway" forKey:@"lastName"];

使用字面量:

mutableArray[1][email protected]"dog";

mutableDictionary[@"lastName"][email protected]"Galloway";



    

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

字面量文法的使用--IOS

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.