2011-01-17 7 views
1

私はNSArraysとNSDictionairesについて読んできました。私は後で必要と思います。私は小さなデータベーステーブルからオブジェクトを設定しようとしています。だから私はレコードIDを介して文字列値にアクセスすることができます。私はこれを何度もやらなければならないので、それをオブジェクトに入れることは理にかなっています。Obj-c、NSDictionaryを作成して関数から値を取得する関数を作成するにはどうすればよいですか?

私は基本を持っている...あなたは間違ってメソッド呼び出している

- (void)viewDidLoad { 

// WORKING START 
NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init]; 
[dictCategories setValue:@"Utility" forKey:@"3"]; 
[dictCategories setValue:@"Cash" forKey:@"5"]; 

NSString *result; 
result = [dictCategories objectForKey:@"3"]; 

NSLog(@"Result=%@", result); 
// WORKING END 

    // Can't get this bit right, current error Request for member 
    // 'getCategories' in something not a structure or union 
NSMutableDictionary *dictCategories2 = self.getCategories; 

NSLog(@"Result2=%@", [dictCategories2 objectForKey:@"5"]); 

[super viewDidLoad]; 
} 

-(NSMutableDictionary*)getCategories { 

NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init]; 

[dictCategories setValue:@"Utility" forKey:@"3"]; 
[dictCategories setValue:@"Cash" forKey:@"5"]; 

return dictCategories; 

} 

答えて

1

、[自己getCategories]を試す

0

あなたは働くが、いくつかされていないものに明確にされていません明らかに間違っていること(JonLOoがあるかもしれません)...

最初に。あなたが間違った方法を使っている、あるいは少なくとも良い方がある - setValue:forKey:setObject:forKey:でなければなりません。これはあなたの問題の理由の1つかもしれません。

次に。あなたは過剰配分であり、適切に解放していません。あなたのviewDidLoaddictCategories2は空白に消えて、getCategoriesメソッドで定義されたdictCategoriesの割り当てメモリを持ってきます。このための簡単な標準修正は、システムによって、後者の方法を使用して自動解放する

NSMutableDictionary *dictCategories = [NSMutableDictionary dictionary]; 

getCategories

NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init]; 

を変更することです。

第3です。あなたは@propertyで読んでみたいです。 getFoo、setBarの代わりにOb-C標準は@propertiesを使用してsetterとgetterメソッドを定義します。これらをオーバーライドして、必要に応じてデフォルトのデータをメソッドに取り込むことができます。また、(おそらく)辞書を、いつでも割り当て解除するのではなく、インスタンス変数としてインターフェイスに格納したいと思っています。これを行う@propertyの実装例:viewDidLoadメソッドで

@interface foo { 
    NSMutableDictionary *ingredients; 
} 

@property (nonatomic, retain) NSMutableDictionary *ingredients; 

@end 

// .... 

@implementation foo 

@synthesize ingredients; 

// ... 

// the @synthesize command above will create getter and setter methods for us but 
// we can override them, which we need to do here 

- (NSMutableDictionary *)ingredients 
{ 
    if (ingredients != nil) { 
     // we've already got an ingredients variable so we just return it 
     return ingredients; 
    } 
    // we need to create ingredients 
    ingredients = [[NSMutableDictionary alloc] init]; 
    [ingredients setObject:@"foo" forKey:@"bar"] 
    return ingredients; 
} 

(またはどこか他のあなたはingredientsがまだ初期化されていないかもしれないと思う場合)、あなたが例えばだろうどこでも他の

NSMutableDictionary *dict = self.ingredients; 

あなたはselfせずにただingredientsを使用することを選ぶことができますが、それがnilだ場合、あなたのメソッドが呼び出されることはありません、とあなたはnilがあなたにスローされます。

これは多くの場合に便利です。これは、クラスの外から成分の変数を読み書きする場合に必要です。あなたが尋ねているものの外ですが、self.getCategoriesと似たようなことをしようとしているので、私はそれを持ってきました。

希望に役立ちます。

関連する問題