47
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-C のリテラルとシンタックスシュガー

Posted at

Objective-C は何かと長々としたメソッドを使う必要があるが、基本の型についてはシンタックスシュガーが用意されている。

NSNumber

定数の前に @ を付けると NSNumber として扱われる。

    NSNumber* n1 = @42;
    NSNumber* n2 = @1.5;
    NSNumber* n3 = @33LL;
    NSNumber* n4 = @YES;
# ifdef __cplusplus
    NSNumber* n5 = @false;
# endif
    NSNumber* n6 = @'a';
    NSNumber* n7 = @(INT_MAX);
    NSNumber* n8 = @(M_PI / 2.0);

NSString

C の文字列(const char*)も NSString にできる。

    NSString* s1 = @"test";
    NSString* s2 = @(getenv("PATH"));

NSArray, NSMutableArray

@[] で NSArray を生成できる。
NSMutableArray にそのまま代入して使うことはできない。

またインデクサを使った参照と更新が可能。
飛び石にならない追加に限っては行える模様。

    NSArray* a1 = @[@"test", @21, @1.2];
    for (id obj in a1) {
        NSLog(@"value = %@", obj);
    }
    NSLog(@"i=1: %@", a1[1]);
    
    NSMutableArray* a2 = [NSMutableArray new];
    a2[0] = @1;
    a2[1] = @2;
    a2[2] = @4;
    NSLog(@"a2=%@", a2);

NSDictionary, NSMutableDictionary

@{} で NSDictionary を生成できる。
NSArray 同様インデクサが使える。

    NSMutableArray* a2 = [NSMutableArray new];
    a2[0] = @1;
    a2[1] = @2;
    a2[2] = @4;
    NSLog(@"a2=%@", a2);
    
    NSDictionary* d1 = @{@1: @"富士", @2: @"鷹", @3: @"なすび"};
    for (id key in d1) {
        NSLog(@"%@ => %@", key, d1[key]);
    }
    
    NSMutableDictionary* d2 = [NSMutableDictionary new];
    d2[@"hello"] = @"こんにちは";
    d2[@"thanks"] = @"ありがとう";
    NSLog(@"d2=%@", d2);
47
46
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
47
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?