6
6

More than 5 years have passed since last update.

NSString の空文字、nil判定について

Posted at

調査したのでメモ

test.m

    NSString *str = @"";

    if(!str) {
        printf("AAAA");
    } else {
        // こちらが呼ばれる
        printf("BBBB");
    }
test.m
    NSString *str = nil;

    if(!str) {
        // こちらが呼ばれる
        printf("AAAA");
    } else {
        printf("BBBB");
    }

なるほど。
空文字列かnilという判定をしたい場合にはこの書き方だと駄目。

NSStringの空チェック

書いてあった。

test.m
    NSString *str = @"";

    if([str length] == 0) {
        // こっちが呼ばれる
        printf("empty");
    } else {
        printf("no empty");
    }
test.m
    NSString *str = nil;

    if([str length] == 0) {
        // こっちが呼ばれる
        printf("empty");
    } else {
        printf("no empty");
    }

想定通りに動いた!

6
6
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
6
6