i have a NSDictionary
which looks like:
{
"Item1" = 2.4;
"Item2" = 5.5;
"Item3" = 15.6;
}
To use this NSDictionary
Items in a Table View i have to transfer it to a NSArray
, am i right?
So i try:
NSDictionary *dict = [myDict objectForKey:@"items"];
for (id item in dict) {
[_myArray addObject:[dict objectForKey:item]];
}
But _myArray keeps empty? What am i doing wrong?
This question is related to
objective-c
nsarray
nsdictionary
You can create an array of all the objects inside the dictionary and then use it as a datasource for the TableView.
NSArray *aValuesArray = [yourDict allValues];
NSArray *keys = [dictionary allKeys];
NSArray *values = [dictionary allValues];
This code is actually used to add values to the dictionary
and through
the data to an Array
According to the Key
.
NSMutableArray *arr = [[NSMutableArray alloc]init];
NSDictionary *dicto = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"Hello",@"StackOverFlow",@"Key1",@"StackExchange",@"Key2", nil];
NSLog(@"The dictonary is = %@", dicto);
arr = [dicto valueForKey:@"Key1"];
NSLog(@"The array is = %@", arr);
You just need to initialize your NSMutableArray
NSMutableArray *myArray = [[NSMutableArray alloc] init];
There are a few things that could be happening here.
Is the dictionary you have listed the myDict
? If so, then you don't have an object with a key of @"items"
, and the dict
variable will be nil. You need to iterate through myDict
directly.
Another thing to check is if _myArray
is a valid instance of an NSMutableArray. If it's nil, the addObject:
method will silently fail.
And a final thing to check is that the objects inside your dictionary are properly encased in NSNumbers (or some other non-primitive type).
NSArray * values = [dictionary allValues];
Code Snippet1:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];
Code Snippet2: If you want to add further
[array addObject:value1];
[array addObject:value2];
[array addObject:value3];
And so on
Also you can store key values of dictionary to array
NSArray *keys = [dictionary allKeys];
To get all objects in a dictionary, you can also use enumerateKeysAndObjectsUsingBlock:
like so:
NSMutableArray *yourArray = [NSMutableArray arrayWithCapacity:6];
[yourDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[yourArray addObject:obj];
}];
+ (NSArray *)getArrayListFromDictionary:(NSDictionary *)dictMain paramName:(NSString *)paramName
{
if([dictMain isKindOfClass:[NSDictionary class]])
{
if ([dictMain objectForKey:paramName])
{
if ([[dictMain objectForKey:paramName] isKindOfClass:[NSArray class]])
{
NSArray *dataArray = [dictMain objectForKey:paramName];
return dataArray;
}
}
}
return [[NSArray alloc] init];
}
Hope this helps!
In Swift 4:
let dict = ["Item1":2.4, "Item2": 5.4, "Item3" : 6.5]
let array = Array(dict.values)
Source: Stackoverflow.com