2016-12-08 39 views
1

我有一個iOS應用程序匹配傳入的文本字段標準字段用於導入記錄。我的問題是,使用這些字段的NSMutableDictionary是空的!這裏是保存的映射的​​代碼:單身漢詞典是空的,我不明白爲什麼

-(void)mapUserFields: (id) sender { // move contents of each textField when user has finished entering it 

    SingletonDictionary *sd = [SingletonDictionary sharedDictionary]; 

    UITextField *tf = (UITextField *)sender; // textfield contains the pointer to user's half of the equation 
    int tagValue = (int)tf.tag; // get the tag value 

    [sd.dictionaryOfUserIndexes setObject:tf.text forKey:[NSString stringWithFormat:@"%d", tagValue]]; // value found in textField id'd by tag 

    NSLog(@"\nfield.text: %@ tagValue: %d nsd.count: %d\n",tf.text, tagValue, sd.dictionaryOfUserIndexes.count); 

} 

這是NSLog的結果:

field.text:1 tagValue:38 nsd.count:0

這是.h文件中單例的定義:

@property (nonatomic, retain) NSMutableDictionary *dictionaryOfUserIndexes; 

這是初始化唱歌的代碼leton在.m文件:

//-- SingletonDictionaryOfUserIDs -- 
+ (id) sharedDictionary { 

    static dispatch_once_t dispatchOncePredicate = 0; 
    __strong static id _sharedObject = nil; 
    dispatch_once(&dispatchOncePredicate, ^{ 
     _sharedObject = [[self alloc] init]; 
    }); 

    return _sharedObject; 
} 

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

@end 

我相信我的問題是,因爲sd.dictionaryOfUserIndexes尚未被初始化,但我不知道這是不是真的,如果是的話,如何對其進行初始化(我試過幾個不同的變體,所有這些都造成了構建錯誤)。我看着SO和Google,但沒有發現解決這個問題的東西。幫助將不勝感激!

+0

顯示如何在單例類中聲明'dictionaryOfUserIndexes'。並請格式化您的代碼。您發佈的問題太多,無法發佈格式不正確的代碼。 – rmaddy

+0

更好的是:格式化我的代碼?如果不是,我不明白你指的是什麼......請詳細說明...... SD – SpokaneDude

+0

'SingletonDictionary'繼承自什麼? –

回答

1

有一些事情是我們可以改善這個代碼,但唯一它是在init方法的參考dictionaryOfUserIndexes。該代碼張貼不會編譯,除非:(a)你有這樣一行:

@synthesize dictionaryOfUserIndexes = dictionaryOfUserIndexes; 

使後盾變量而沒有默認_前綴命名,或(b)你指的是與伊娃缺省前綴,如:

_dictionaryOfUserIndexes = [NSMutableDictionary new]; 

的另一種方式 - 在除了一個init方法中最每個上下文優選 - 是使用合成的設定器,如:

self.dictionaryOfUserIndexes = [NSMutableDictionary new]; 

但是機智h單獨更改(所以它會編譯)您的代碼運行正常,向字典添加一個值並記錄遞增計數。

+0

非常感謝你...我真的很感激... – SpokaneDude