[英]How can I access properties from an NSArray?
我從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”(在上述文件中)。 類“數據”定義了這四個屬性。
現在,我想在快速文件中的圖表內部顯示這些屬性。 例如,我想在x軸上顯示“ messzeitpunkt”,在y軸上顯示“ pulse”。 我知道如何處理圖表,但我的問題是我不知道如何訪問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>"
)
這正是您想要和期望的! 您有四個Data對象的數組。 唯一的問題是您忘了告訴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數組中的內容。 然后,您將看到數據完全符合您的預期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.