我正在尝试将NSDictionary
数据放入tableView
。但是当只有一个值时,我遇到了问题。
这里,一个“上传”计数返回8(但它应该返回1),如果有多个“上传”计数,则返回“上传”的数量,因为它应该是第一种情况。 / p>
NSDictionary *jsonDictionary = aDicLog;
NSMutableArray *tableData = jsonDictionary[@"multimedia"][@"uploads"][@"upload"];
int count = [tableData count];
NSLog(@"COUNT: %i", count);
表格
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tableData count];
}
细胞
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//App Crashes in this line
NSDictionary *ldUpload = [tableData objectAtIndex:indexPath.row];
...
return cell;
}
例外,有一个“上传”:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM objectAtIndex:]: unrecognized selector sent to instance
字典看起来像这样:
以下是应用崩溃的原因:(只有一个“上传”)
Printing description of tableData:
{
FileName = {
text = "IMG_0510.MOV";
};
status = {
text = 2;
};
Event = {
text = Q;
};
Date = {
text = "9/9/2016 11:01:58 AM";
};
Publicacion = {
text = "Example";
};
Seccion = {
text = Sistemas;
};
idMultimedia = {
text = 1136;
};
text = "";
}
以下是该应用运行良好的情况:(有多个“上传”)
Printing description of tableData:
<__NSArrayM 0x7a49dc90>(
{
FileName = {
text = "1-FB5A9792.MOV";
};
status = {
text = 4;
};
Event = {
text = Test;
};
Date = {
text = "9/7/2016 9:06:21 AM";
};
Publicacion = {
text = "Example";
};
Seccion = {
text = Sistemas;
};
idMultimedia = {
text = 993;
};
text = "";
},
{
FileName = {
text = "2-FB5A9793.MOV";
};
status = {
text = 4;
};
Event = {
text = Test;
};
Date = {
text = "9/7/2016 9:06:21 AM";
};
Publicacion = {
text = "Example";
};
Seccion = {
text = Sistemas;
};
idMultimedia = {
text = 994;
};
text = "";
},...
我使用XMLReader将XML转换为Dictionary
,然后将上述数据传递给tableData
XML
<multimedia>
<uploads>
<upload>
<id>1136</id>
<Date>9/9/2016 11:01:58 AM</Date>
<FileName>IMG_0510.MOV</FileName>
<status>2</status>
<Publicacion>Example</Publicacion>
<Seccion>Sistemas</Seccion>
<Event>Q</Event>
</upload>
</uploads>
</multimedia>
如果只有1个“上传”,如何返回1而不是8,如果是“上传”,则如何返回n?
答案 0 :(得分:2)
您可以在生成tableData数组的基础上检查对象类型以及它是Dictionary
还是NSArray
。
id uploadsObj = jsonDictionary[@"multimedia"][@"uploads"][@"upload"];
if ([uploadsObj isKindOfClass:[NSDictionary class]]) {
NSMutableArray *tableData = [NSMutableArray arrayWithObject:(NSDictionary*)uploadsObj];
}
else if ([uploadsObj isKindOfClass:[NSArray class]]) {
NSMutableArray *tableData = [NSMutableArray arrayWithArray:(NSArray*)uploadsObj];
}
答案 1 :(得分:1)
Swift版本:
只需检查数据是字典还是数组:
var tableData:[[String:AnyObject]]! = []
if let data = jsonDictionary[@"multimedia"][@"uploads"][@"upload"] as? [String:AnyObject] {
print("Single upload data")
tableData.append(data)
} else {
if let data = jsonDictionary[@"multimedia"][@"uploads"][@"upload"] as? [[String:AnyObject]] {
print("multiple upload data")
tableData = data
}
}