我正在从 MySQL 数据库中获取 JSON 格式的数据。在 Objective-C 文件中,数据被修改并放入 NSMutableArray(“_data”)。通过函数“itemsDownloaded”,代理会在从数据库下载完成并收到“_data”数组后立即收到通知。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the data
NSMutableArray *_data = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new data object and set its props to JsonElement properties
Data *newData = [[Data alloc] init];
newData.sozialversicherungsnummer = jsonElement[@"Sozialversicherungsnummer"];
newData.messzeitpunkt = jsonElement[@"Messzeitpunkt"];
newData.puls = jsonElement[@"Puls"];
newData.sauerstoffgehalt = jsonElement[@"Sauerstoffgehalt"];
// Add this question to the locations array
[_data addObject:newData];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_data];
}
我的目标是访问“newData”(在上述文件中)的属性“sozialversicherungsnummer”、“messzeitpunkt”、“puls”和“sauerstoffsättigung”。 “数据”类定义了这四个属性。
现在我想在 swift 文件 的图表内显示这些属性。例如,我想在 x 轴上显示“messzeitpunkt”,在 y 轴上显示“puls”。我知道如何处理图表,但我的问题是我不知道如何访问 swift 文件中的属性。
如果我将这些行写入我的 swift 文件:
var data: NSArray = [];
func itemsDownloaded(items: [AnyObject]!) {
data = items
print("\(data)")
}
我在输出中得到了这个:
(
"<Data: 0x7ca5ff60>",
"<Data: 0x7ca5dab0>",
"<Data: 0x7be497e0>",
"<Data: 0x7ca42c00>"
)
有人可以帮助我吗?
最佳答案
问题是您不需要 NSArray。 Swift 不知道 NSArray 里面有什么。您需要一个 Swift 数组,即 [Data]
。这样,Swift 就知道每个项目都是一个数据,您可以访问它的属性。
你的输出是:
(
"<Data: 0x7ca5ff60>",
"<Data: 0x7ca5dab0>",
"<Data: 0x7be497e0>",
"<Data: 0x7ca42c00>"
)
而这正是您想要和期待的!您有一个包含四个数据对象的数组。唯一的问题是你忘了告诉 Swift 这件事。您需要将数组键入为 [Data]
或将其转换为 [Data]
。
例如,你现在说的是:
func itemsDownloaded(items: [AnyObject]!) {
data = items
print("\(data)")
}
试着这样说:
func itemsDownloaded(items: [AnyObject]!) {
let datas = items as! [Data]
datas.forEach {print($0.messzeitpunkt)}
}
这是合法的,因为现在你已经告诉 Swift 数组中有什么。您会看到您的数据就在那里,完全符合您的预期。
关于ios - 如何从 NSArray 访问属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34686718/