2011-11-30 42 views
-1

我需要動態地創建和銷燬詞典,或陣列, 並將它們作爲實例變量,目標C如何動態創建詞典和參考它們

所以例如[僞]

* .H

nsmutableDictionary myDictn??? 
nsstring arrayn ??? 

如何創建一個實例dictionarie和財產,這dinamically獲得創建和銷燬?以及如何參考呢?

* .M

n = 0 
create container { 
    myDictn alloc init 
n+1 
} 



other { 
myDictn [email protected]"data" forKey"myKey" 

} 

destroy container { 
myDictn release 
n-1 
} 

那麼什麼打算顯示的是,我想有myDict1,myDict2 ... 如果創建的話, 或者如果需要

摧毀他們

非常感謝!

+0

那麼爲什麼投票呢?這是明顯的嗎? – MaKo

+0

我認爲你的問題不是很清楚。使用字典的基本功能在那裏(alloc/init,addObject:forKey:,release),所以你可能會更具體。 –

+0

我認爲這是因爲你不清楚你在問什麼。 –

回答

1

我想你問因爲是如何動態創建多個可變字典。您尚未說明編號方案來自哪裏,因此您可能需要根據自己的目的修改此解決方案。

你想要的是一個數組或詞典的字典。

讓一個NSMutableDictionary叫做dictionaryContainer。然後,當你想創建字典7號,做

NSMutableDictionary *aDictionary = [NSMutableDictionary new]; 
[dictionaryContainer setObject:aDictionary forKey:[NSNumber numberWithInt:7]]; 

要記得字典,做

NSMutableDictionary *theSameDictionary = [dictionaryContainer objectForKey:[NSNumber numberWithInt:7]]; 

你不必硬編碼的7,你可以從任何地方得到它,作爲一個整數變量傳遞它。

1

要創建詞典動態&條目添加到他們,你可以做到這一點 -

NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] retain]; 
[dictResult setValue:result forKey:@"key"]; 

這裏result可以是任何東西。 NSStringNSArray等。同樣使用retain保留此對象&如果未明確釋放,則會導致內存泄漏。相反,請嘗試執行autorelease這種方式ios負責在不再提及時釋放對象。你這樣做 -

NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] autorelease]; 

這就是你需要動態創建字典的全部內容。

+0

嗨,謝謝,但我需要不同的dictResult .. dictResult1,dictResult2,dictResult3;並能夠引用他們,是否有更好的方法來實現這一目標? – MaKo

+0

在循環中創建不同的'dictResult'實例並將它們插入到'NSArray'中。如果你想要不同的名字,那麼在循環中使用'if-else'。但我會建議前者。 –

1

如果我正確了你的問題,這是很容易

@interface MyClass { 
    NSMutableDictionary *dict; 
    NSMutableArray *arr; 
} 

@property (nonatomic, retain) NSMutableDictionary *dict; 
@property (nonatomic, retain) NSMutableArray *arr; 

@end 

實現文件

@import "MyClass.h" 

@implementation MyClass 

@synthesize dict; 
@synthesize arr; 

- (id) init { 
    self = [super init]; 
    if (self) { 
    dict = [[NSMutableDictionary alloc] init]; 
    arr = [[NSMutableArray alloc] init]; 
    } 
    return self; 
} 

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

- (void) otherStuff { 

    [dict setObject: @"value" forKey: @"key"]; 
    [arr addObject: @"item"]; 

} 

@end 

從另一個類的用法:

... 
MyClass *instance = [MyClass new]; 
[instance.dict setObject: @"value" forKey: @"key"]; 
NSLog(@"Array items: %@", instance.arr); 
[instance release]; 
...