2011-11-30 66 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]; 
...