我有这样的 View Controller 类
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (nonatomic, strong) NSDictionary *dictionary;
@end
ViewController.m
#import "ViewController.h"
#import "GoogleMaps.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//HOW TO ACCESS THE PROPERTY VALUE HERE
self.dictionary = @{};
/ DUMP ALL FOUND ITEMS
for(DummyContainer* geoItem in geoItems) {
NSDictionary *item = @{
@"latitude":geoItem.latitude,
@"longtitude":geoItem.longtitude
};
self.dictionary[geoItem.geoPoint.name] = item;
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
预期的格式是
var container = {
'location':{
'latitude':1233,
'longtitude':124
}
}
这可以通过访问
let obj = container['location'];
对于这样的纬度访问
obj.latitude;
- 问题1:如何创建类属性作为字典并在类内部访问?
- 问题 2:如何创建 JSON 结构并访问值?
我是 iOS 的新手,请帮助我提前谢谢。
最佳答案
用于创建不可扩展/不可变的字典对象
@property (strong, nonatomic) NSDictionary *myClassDictionary;
用于创建可扩展/可变字典对象
@property (strong, nonatomic) NSMutableDictionary *myClassMutableDictionary;
将所有值插入字典中,如下所示 你的例子数据
'location':{
'latitude':1233,
'longtitude':124
}
NSDictionary *dict = @{@"lattitude":@"1233" , @"longitude":@"124"};
self.myClassDictionary = @{@"location":dict};//Convert this dictionary into JSON.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: self.myClassDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString jsonString;
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
关于ios - 如何在类属性中的 Objective C 中创建类似 json 的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40866818/