2009-07-10 118 views
29

在下面的代碼中,第一個日誌語句顯示爲預期的小數,但第二個日誌爲NULL。我究竟做錯了什麼?創建NSDictionary

NSDictionary *entry = [[NSDictionary alloc] initWithObjectsAndKeys: 
    @"x", [NSNumber numberWithDouble:acceleration.x], 
    @"y", [NSNumber numberWithDouble:acceleration.y], 
    @"z", [NSNumber numberWithDouble:acceleration.z], 
    @"date", [NSDate date], 
    nil]; 
NSLog([NSString stringWithFormat:@"%@", [NSNumber numberWithDouble:acceleration.x]]); 
NSLog([NSString stringWithFormat:@"%@", [entry objectForKey:@"x"]]); 
+2

在一個不相關的說明中,[的NSString stringWithFormat:]位是不必要的,並且可能有害。你應該像這樣調用NSLog:NSLog(@「%@」,[entry objectForKey:@「x」]);. NSLog的第一個參數是一個格式字符串,它應該總是一個文字。 – 2009-07-10 07:36:21

回答

103

您正在交換您插入對象和關鍵字的順序:您需要先插入對象,然後按照以下示例所示插入關鍵字。

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil]; 
+1

如果您的值正在動態放置,請注意任何值爲空的情況。這可以使您的字典的創建在中間停止,因爲`nil`是方法調度中的哨兵。根據需要進行驗證。 'NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:@「value1」?nil:@「」,@「key1」,@「value2」?nil:@「」,@「key2」,nil];` – 2017-01-27 20:19:57

5

的NSDictionary語法:

NSDictionary *dictionaryName = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@value2",@"key2", nil]; 

實施例:

NSDictionary *importantCapitals = [NSDictionary dictionaryWithObjectsAndKeys: 
@"NewDelhi",@"India",@"Tokyo",@"Japan",@"London",@"UnitedKingdom", nil]; 
NSLog(@"%@", importantCapitals); 

輸出看起來像,

{印度=新德里;日本=東京;聯合王國=倫敦; }

14

新的Objective-c支持這種靜態初始化的新語法。

@{key:value} 

例如:

NSDictionary* dict = @{@"x":@(acceleration.x), @"y":@(acceleration.y), @"z":@(acceleration.z), @"date":[NSDate date]}; 
+0

` [NSNumber numberWithDouble:acceleration.x]`也可以縮寫爲`@(acceleration.x)` – 2015-06-02 09:38:34

相關問題