2012-02-23 66 views
0

林無法理解返回空值爲何下面的代碼顯示「第一密鑰=(空)」在控制檯/終端:的NSDictionary關鍵

這裏是接口:

#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 

在此先感謝!

回答

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]; 
+0

工作!謝謝!你今天教給我一個非常寶貴的教訓! – Moose 2012-02-23 23:39:44