2009-07-10 110 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

相关问题