2014-02-23 26 views
2

有以下類的NSMutableDictionary *屬性修改的NSMutableDictionary類屬性不是方法

@interface MyClass : NSObject 
@property(retain,atomic) NSMutableDictionary* dict; 
- (void) method; 
@end 

- (id) init{ 
    self = [super init]; 
    if(self){ 
     self.dict = [NSMutableDictionary dictionary]; 
    } 

    return self; 
} 
- (void) method 
{ 
    NSMutableDictionary* dict = [NSMutableDictionary dictionary]; 
    self.dict[@"Test"] = @"Shmest"; 
    dict[@"Test"] = @"Shmest"; 
    NSLog(@"Count: %ld",[self.dict allKeys].count); 
    NSLog(@"Count: %ld",[dict allKeys].count); 
} 

輸出是

2014-02-23 19:05:44.110 MyProj[12818:303] Count: 0 
2014-02-23 19:05:44.110 MyProj[12818:303] Count: 1 

爲什麼self.dict沒有被修改?

UPD 使用MyClass * obj = [MyClass alloc]代替MyClass * obj = [[MyClass alloc] init],所以init還沒有被調用。

+0

你在任何地方設置self.dict?在爲dict屬性設置值之前,它將爲零,因此其行爲就像它在代碼中一樣。 – Ryan

+0

我在init方法中設置它(添加到post body) –

+0

將'NSLog(dict)'添加到'method'來檢查它是否被初始化。 – Avt

回答

0

有必要實例化dict屬性,這可以在init方法中完成。

樣品:

- (instancetype)init { 
    self = [super init]; 
    if (self) { 
     _dict = [NSMutableDictionary new]; 
    } 
    return self; 
} 

調用具有:

MyClass *myClass = [MyClass new]; 
[myClass method]; 
+0

請看看我添加到的'init'方法。有什麼不對? ('new','dictionary'和'alloc'的行爲方式相同:新值不加dict) –

+0

我剛測試過你的代碼,它工作正常。我不得不添加'@implementation MyClass'和結尾'@ end'。 – zaph

相關問題