使用字面量文法讓iOS代碼更漂亮

來源:互聯網
上載者:User

標籤:字面量文法

字面量文法
第一、字面數值
    複雜方法:
        NSNumber *someNumber=[NSNumber numberWithDouble:3.4];
        NSLog(@"the value is %@",someNumber);
    替代方法:
        NSNumber *[email protected];
        NSNumber *[email protected];
        NSLog(@"the value is %@",a);

        NSLog(@"the value is %@",b);


第二、字面數組
  複雜方法:
        NSArray *arr=[NSArray arrayWithObjects:@"hello",@"richard",@"yang", nil];
        NSLog(@"the first object is %@",[arr objectAtIndex:0]);
    替代方法
        NSArray *[email protected][@"hello",@"richard",@"yang"];
        NSLog(@"the first object is %@",arr1[1]);
    注意事項:

        用字面量文法建立數組時,若有元素對象為nil,則會拋出異常,而用arrayWithObjects建立,nil前面的資料可以正確建立

第三、字面量字典
  複雜方法:
      NSDictionary *personDic=[NSDictionary dictionaryWithObjectsAndKeys:@"richard",@"name",@"001",@"num", nil];
        NSLog(@"name is %@",[personDic valueForKey:@"name
    替代方法:
        NSDictionary *[email protected]{@"name":@"richard",@"num":@"001"};

        NSLog(@"the name is %@",personDic[@"name"]);


第四、常見可變對象
        NSMutableArray *arr1=[@[@"hello",@"richard",@"yang"] mutableCopy];

        使用字面量文法建立的可變對象時需要加上mutaleCopy


第五、使用字面量文法修改值
        NSMutableArray *arr1=[@[@"hello",@"richard",@"yang"] mutableCopy];
        NSLog(@"the first value  is %@",arr1[0]);
        arr1[0][email protected]"andy";

        NSLog(@"the first value  is %@",arr1[0]);


第六、總結
    1、使用字面量文法去建立對象,簡明而要
    2、通過取下標操作來訪問數組與取key操作來訪問字典
    3、用字面值文法建立數組或字典時,若值中有nil,則會拋異常



使用字面量文法讓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.