如何将字典数据添加到数组中?

时间:2013-01-24 06:50:08

标签: objective-c xcode nsarray nsdictionary

我制作了一个数组和一本字典。现在我想把字典的值放到数组中..我对目标C很新,所以请帮助。 “viewcontroller .m”

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

marray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4", nil];
marray = [[NSMutableArray alloc]initWithObjects:@"6",@"7",@"8",@"9",@"10", nil];
[self displayarray];
[marray release];
mDictionary = [[NSMutableDictionary alloc]init];
[mDictionary setValue:@"sdfsdhfg" forKey:@"firstname"];
[mDictionary setValue:@"kvxv" forKey:@"lastname"];
[self displaydict];
[mDictionary release];
}
-(void)displaydict{
CFShow(mDictionary);
}
-(void)displayarray{
for (int i = 0; i<[marray count]; i++) {
    NSLog(@"the array data present at %d index is %@",i,[marray objectAtIndex:i]);
}
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}


@end

3 个答案:

答案 0 :(得分:9)

您的问题包含许多其他问题,我将尝试解决与将字典转换为数组相关的问题。

  1. 存储所有密钥

    NSArray *dictKeys=[dict allKeys];
    
  2. 存储所有值

    NSArray *dictValues=[dict allValues];
    
  3. 如果您想存储密钥和值:

    NSArray *keysAndValues=[dictKeys arrayByAddingObjectsFromArray:dictValues];
    

  4. 编辑:

    当您需要NSMutableArray时,您可以使用:

    NSMutableArray *dictAllKeys=[NSMutableArray arrayWithArray:[dict allKeys]];
    NSMutableArray *dictAllValues=[NSMutableArray arrayWithArray:[dict allValues]];
    NSMutableArray *keysAndValues=[NSMutableArray arrayWithArray:[dictAllKeys arrayByAddingObjectsFromArray:dictAllValues]];
    

答案 1 :(得分:3)

for (NSDictionary *dictionary in arrayname)
{
    NSMutableArray *array = [dictionary objectForKey:@"writeKey"];
}

这可能对您有所帮助

答案 2 :(得分:0)

如果要访问Dictionary的值,请使用特定键作为值。为此使用以下格式。

NSArray *yourarray=[YourDictionary ObjectForKey:@"KEY"];

我希望这会对你有所帮助。