1
// MyClass.h
@interface MyClass : NSObject
{
   NSDictionary *dictobj;
}
@end

//MyClass.m
@implementation MyClass

-(void)applicationDiDFinishlaunching:(UIApplication *)application
{

}
-(void)methodA
{
// Here i need to add objects into the dictionary
}

-(void)methodB
{
//here i need to retrive the key and objects of Dictionary into array
}

私の質問は、methodA と methodB の両方が NSDictionary オブジェクト [ie dictobj] を使用しているためです。このコードをどのメソッドに記述すればよいでしょうか。

dictobj = [[NSDictionary alloc]init];

両方の方法で2回行うことはできません。したがって、どうやってそれを行うのですか?

4

2 に答える 2

2

まず、辞書の内容を変更する必要がある場合は、変更可能にする必要があります。

@interface MyClass : NSObject
{
    NSMutableDictionary *dictobj;
}
@end

通常、次のように、指定された初期化子で dictobj のようなインスタンス変数を作成します。

- (id) init
{
    [super init];
    dictobj = [[NSMutableDictionary alloc] init];
    return self;
}

-dealloc でメモリを解放します。

- (void) dealloc
{
    [dictobj release];
    [super dealloc];
}

(クラス メソッドではなく) インスタンス実装のどこからでもインスタンス変数にアクセスできます。

-(void) methodA
{
    // don't declare dictobj here, otherwise it will shadow your ivar
    [dictobj setObject: @"Some value" forKey: @"Some key"];
}

-(void) methodB
{
    // this will print "Some value" to the console if methodA has been performed
    NSLog(@"%@", [dictobj objectForKey: @"Some key"]);
}
于 2010-02-17T06:40:25.673 に答える
0
-----AClass.h-----
extern int myInt;  // Anybody who imports AClass.h can access myInt.

@interface AClass.h : SomeSuperClass
{
     // ...
}

// ...
@end
-----end AClass.h-----


-----AClass.h-----
int myInt;

@implementation AClass.h
//...
@end
-----end AClass.h-----
于 2010-02-17T07:03:50.357 に答える