在字典中我有Key&价值如下。我如何获得" title"来自下面的值并将其存储在NSArray *数据中?
{
changed = 1414164684;
city = Stockholm;
class = "3. Mycket god klass";
coordinates = "POINT(59.3246206 18.0686084)";
id = 37510;
title = "19 Glas Bar & Matsal";
total = 70;`enter code here`
},
{
changed = 1413991969;
city = "G\U00f6teborg";
class = "2. M\U00e4starklass";
coordinates = "POINT(57.697944330446234 11.974067687988281)";
id = 34865;
title = "28+";
total = 77;
},
答案 0 :(得分:4)
上面提到的代码片段是一个数组,让它命名为" result_Array"。在" result_Array"你正在展示两个对象。每个对象都是字典。从每个词典中,您想要获取标题并将其保存在名为" data"的数组中。我们走了
NSMutableArray *data=[NSMutableArray new];
for(int i=0; i<result_Array.count ; i++)
{
NSDictionary *dict = [result_Array objectAtIndex:i];
[data addObject:[dict objectForKey:@"title"]];
}
希望它有所帮助。随意询问任何查询
答案 1 :(得分:2)
如果您有一个NSDictionary数组,那么您可以使用方法&#34; valueForKey&#34;获取密钥的所有值。没有任何迭代:
NSArray *list = @[
@{@"changed":@"1414164684",
@"title":@"19 Glas Bar & Matsal"},
@{@"changed":@"1413991969",
@"title":@"28+"}];
NSArray *titles = [list valueForKey:"title"];
在数组标题中,您只能从列表中获得标题。
答案 2 :(得分:1)
您提供的示例代码实际上是一个字典数组。所以用这个小改变回答你的问题
NSArray *originalDict;
NSMutableArray *data = [NSMutableArray new];
for (NSUInteger i = 0; i < originalDict.count; i++) {
NSDictionary *currentDictionaryPointer = [originalDict objectAtIndex:i];
NSString *title = [currentDictionaryPointer objectForKey:@"title"];
[data addObject:title];
}
其中originalDict
是指向您提供的示例代码的对象。
答案 3 :(得分:0)
以下示例将使用最少量的代码执行相同操作。
NSMutableArray *arr = [NSMutableArray new];
for (NSDictionary* dict in myArray)
{
[arr addObject:[dict valueForKey:@"title"]];
}
arr
对象将包含键#39;标题#39;的所有值。
答案 4 :(得分:0)
请执行以下步骤以获得答案
1.First of all You should Create NSMutableArray
2.After copy the dictionary to NSMutableArray
NSMutableArray *array = [yourDictionary copy];
3.After that set or create the for loop.
4.Create NSString *strTitle in for loop.
5.Finally strTitle = [NSString stringWithFormat:@"%@",[[array objectAtIndex:i]valueForKey:@"title"]]];
答案 5 :(得分:0)
简单步骤
NSMutableArray *array = [yourDict copy];[If it is your dict is NSMutableDictionary]
or
NSMutableArray *array = [yourDict mutableCopy]; [If it is your dict is NSDictionary];
for(int i=0;i<[array count];i++)
{
NSString *strTitle = [NSString stringWithFormat:@"%@",[[array objectAtIndex:i]valueForKey:@"title"]];
NSLog(@"the title is==%@",strTitle);
}
答案 6 :(得分:0)
如果你得到“一系列东西”,我不会将它存储在Dict中,我会把它存储到NSArray中,然后迭代它就像:
var myObjects:[Object]
var myCollection = yourJSON as NSArray (assuming that you always get the same.
func myStuff (myCollection) {
for item in myCollection {
change = myCollection["changed"] as NSString (assuming a String here)
city = myCollection["city"] as NSString
...
...
var Foo:Object = Object()
Foo.change = change
Foo.city = city
...
...
myObjects.append(Foo)
}
稍后,您现在可以轻松地迭代myObjects数组以在TableView中显示内容