zoukankan      html  css  js  c++  java
  • Effective Objective-C 2.0 Reading Notes

    1. Literal Syntax

    NSString *someString = @"Effective Objective-C 2.0";

    NSNumber *someNumber = [NSNumber numberWithInt:1];

    <=>

    NSNumber *someNumber = @1;

    // syntax also works for expressions

    int x = 5;
    float y = 6.32f;
    NSNumber *expressionNumber = @(x * y);

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

    <=>

    NSArray *animals = @[@"cat", @"dog", @"mouse", @"badger"];

    NSString *dog = [animals objectAtIndex:1];

    <=>

    NSString *dog = animals[1];

    However, you need to be aware of one thing when creating arrays using the literal
    syntax. If any of the objects is nil, an exception is thrown

    a scenario:

    id object1 = /* ... */;
    id object2 = /* ... */;
    id object3 = /* ... */;


    NSArray *arrayA = [NSArray arrayWithObjects:
    object1, object2, object3, nil];


    NSArray *arrayB = @[object1, object2, object3];

    Now consider the scenario in which object1 and object3 point to valid Objective-C
    objects, but object2 is nil. The literal array, arrayB, will cause the exception to be thrown.
    However, arrayA will still be created but will contain only object1. The reason is that the
    arrayWithObjects: method looks through the variadic arguments until it hits nil, which is
    sooner than expected.

    It’s much better that an exception is thrown, causing a probable application crash, rather than creating an array
    having fewer than the expected number of objects in it.

    // Literal Dictionaries

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

    <=>

    NSDictionary *personData =
    @{@"firstName" : @"Matt",
    @"lastName" : @"Galloway",
    @"age" : @28};

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

    <=>

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

  • 相关阅读:
    03.移除相同的元素
    02.计算数组元素之和
    01-找出元素在数组中的位置
    node.js中Content-Type的设置
    node.js接受form表单数据
    node.js创建服务器
    mongoDB笔记
    TDK三大标签SEO(搜索引擎优化)优化
    引入网页图标
    JavaScript实现二叉搜索树
  • 原文地址:https://www.cnblogs.com/davidgu/p/3731526.html
Copyright © 2011-2022 走看看