我试图创建一个应用程序,从api中提取json,并提供一组关于界面的外观样式的说明。所以基本上,json将包含一个NSDictionary数组,每个NSDictionary将是一个显示在屏幕上的对象。以编程方式创建NSObjects ios
在NSDictionary中将显示如何显示对象的所有细节,如对象的类型,对象的位置和对象的大小。
我已经编写代码来接受一组按钮到屏幕。
for (int i = 0; i < self.jsonObjects.count; i++) {
NSDictionary *jsonObject = [self.jsonObjects objectAtIndex:i];
if ([[jsonObject objectForKey:@"object"] isEqualToString:@"UIButton"]) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSNumber *x = [jsonObject objectForKey:@"xlocation"];
NSNumber *y = [jsonObject objectForKey:@"ylocation"];
NSNumber *width = [jsonObject objectForKey:@"width"];
NSNumber *height = [jsonObject objectForKey:@"height"];
NSString *title = [jsonObject objectForKey:@"title"];
[button setFrame:CGRectMake(x.intValue, y.intValue, width.intValue, height.intValue)];
[button setTitle:title forState:UIControlStateNormal];
[self.view addSubview:button];
}
}
现在我可以为每个对象提供大量的if语句并让程序做同样的事情,但我试图避免它。
基本上我所要求的是实现这一点的最佳方式是尽量减少编码并提高代码的可读性。
这是我写的模仿json输出按钮的代码。
NSDictionary *button = [[NSDictionary alloc] initWithObjectsAndKeys:@"UIButton", @"object",@"PressMe",@"title",@"10",@"xlocation",@"10",@"ylocation",@"100",@"width",@"100",@"height", nil];
NSDictionary *button2 = [[NSDictionary alloc] initWithObjectsAndKeys:@"UIButton", @"object",@"Dont Press",@"title",@"10",@"xlocation",@"210",@"ylocation",@"100",@"width",@"100",@"height", nil];
self.jsonObjects = [[NSArray alloc] initWithObjects:button,button2, nil];
由于我仍然必须创建api,所以json输出可以非常灵活。我正想着有一个数组的数组。其中数组中的每个数组都是一组按钮或文本字段数组。那么我只需要大约20-30个数组来覆盖不同的对象类型,并且可以遍历主数组,然后遍历每个按钮或文本字段的数组。
为礼Ganem
object UIView * 0x07145c60
UIResponder UIResponder
_layer CALayer * 0x07145e80
_tapInfo id 0x00000000
_gestureInfo id 0x00000000
_gestureRecognizers NSMutableArray * 0x00000000
_subviewCache NSArray * 0x075213e0
_charge float 0
_tag NSInteger 0
_viewDelegate UIViewController * 0x00000000
_backgroundColorSystemColorName NSString * 0x00000000
_viewFlags <anonymous struct>
坦率地说,坚果是开始编码,并丢弃前3-4次尝试。你最终会理解这些问题,并以合理的方式解决问题。 – 2013-04-09 12:15:03