NSDictionary为key返回null值

时间:2012-02-23 23:30:05

标签: objective-c ios xcode

我无法理解为什么以下代码在控制台/终端中显示“The First Key =(null)”:

这是界面:

#import <UIKit/UIKit.h>

@interface TestingViewController : UIViewController

@property (nonatomic, strong) NSMutableArray *namesArray;
@property (nonatomic, strong) NSDictionary *myDictionary; 

@end

这是实施:

#import "DictionaryTestViewController.h"

@implementation DictionaryTestViewController

@synthesize namesArray;
@synthesize myDictionary;

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.myDictionary initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
    NSLog(@"The First Key = %@", [self.myDictionary objectForKey:@"key1"]);
}

@end

提前致谢!

1 个答案:

答案 0 :(得分:5)

你还没有分配你的字典。它目前只有nil,并且向nil发送消息不会做任何事情。

如果您正在使用ARC

,请将其更改为此
self.myDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];

或者如果不是

self.myDictionary = [[[NSDictionary alloc] initWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil] autorelease];