簡體   English   中英

如何從NSDictionary數組獲取值數組

[英]How to get array of values from NSDictionary array

當我嘗試在日志中打印json值數組時,我得到的是地址而不是值。 這是我的編碼方式。

NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
            NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
            NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
            NSMutableArray *anotherTempArray = [NSMutableArray arrayWithCapacity:jsonArray.count];
            NSDictionary *dict;
            for(dict in jsonArray)
            {
                NSString *projectName = dict[@"Name"];

                NSString *urlText = dict[@"Url"];
                NSLog(@"Url text in array = %@", urlText);

                NSString *attch = dict[@"attachmentes"];
                NSLog(@"Attached url in array = %@", attch);

                NSString *projID = dict[@"ProjectID"];
                NSLog(@"Project ID in array = %@", projID);

                SaveAttachment *saveAt = [[SaveAttachment alloc] initWithName:projectName withList:@"View"     withAttachment:@"View"];
                [tempArray addObject:saveAt];

                SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
                saveProj.projectId = projID;
                [anotherTempArray addObject:saveProj];
             }
            array = tempArray;
            [self.tableViewProject reloadData];
            NSLog(@"Array of project IDs === %@", anotherTempArray); //Get values (array of project ids here.

        }

在此處輸入圖片說明

更換

SaveProjectId *saveProj = [[SaveProjectId alloc] initWithProjectId:projID];
saveProj.projectId = projID;
[anotherTempArray addObject:saveProj];

[anotherTempArray addObject:projID];

這是因為您的anotherTempArray包含SaveProjectId的對象,即,每次在for循環中,您都添加的是saveProj對象而不是projID 這就是為什么您的數組顯示SaveProjectId對象的原因。

如果要直接保存它們,請使用以下修改

[anotherTempArray addObject:projID];

或者您可以使用like(這是我希望的)

NSLog(@"First project ID === %@", [anotherTempArray objectAtindex:0] projectId]);

您正在將SaveProjectId對象存儲在數組中,因此,在打印內容時,您會看到這些對象的地址。

您的“ anotherTemoArray”具有SaveProbectId的對象,因此您必須將索引處的對象傳遞給SaveProjectId,然后才能看到數組信息

當調用NSLog(@"Array of project IDs === %@", anotherTempArray); 正在調用“ anotherTempArray”內部的每個對象的-(NSString*)description方法。

在您的情況下,這意味着在SaveProjectId對象上調用-(NSString*)description 覆蓋它以打印出您想要的...例如

-(NSString*)description {
    return [NSString stringWithFormat:@"SaveProjectId: %@",self.projectId];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM