工厂模式很好用,为表诚意,我直接搞个实用的例子放这,解析一个订单的数据,并且这个订单里面可能不止一件商品的做法。
还是直接上代码,不懂的地方,再提出来。
1.在MyOrderDeals.h文件中
#import <Foundation/Foundation.h>
@interface MyOrderDeals : NSObject
@property(nonatomic,strong) NSString *id;
@property(nonatomic,strong) NSString *orderID;
@property(nonatomic) float allMoney;
@property(nonatomic) float transportationCost;
@property(nonatomic,strong) NSMutableArray *goodsArr;
+(id)myOrderDealsWithDict:(NSDictionary*)dict;
@end
2.在MyOrderDeals.m文件中
#import "MyOrderDeals.h"
#import "SingleOrderCellDeal.h"
@implementation MyOrderDeals
+(id)myOrderDealsWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
-(id)initWithDict:(NSDictionary*)dict{
self = [super init];
if (self) {
self.id = dict[@"id"];
self.orderID = dict[@"order_sn"];
self.allMoney = [dict[@"pay_amount"] floatValue];
self.transportationCost = [dict[@"delivery_fee"] floatValue];
self.goodsArr = [NSMutableArray array];
for (NSDictionary *singleDealDict in dict[@"goods"]) {
SingleOrderCellDeal *deal = [SingleOrderCellDeal singleOrderDealCellWithDict:singleDealDict];
[self.goodsArr addObject:deal];
}
}
return self;
}
@end
3.在SingleOrderCellDeal.h文件中
#import <Foundation/Foundation.h>
@interface SingleOrderCellDeal : NSObject
@property(nonatomic,strong) NSString *title;
@property(nonatomic) float currentPrice;
@property(nonatomic,strong) NSString *selledCount;
@property(nonatomic,strong) NSURL *imageURL;
+(id)singleOrderDealCellWithDict:(NSDictionary*)dict;
@end
4.在SingleOrderCellDeal.m文件中
#import "SingleOrderCellDeal.h"
@implementation SingleOrderCellDeal
static NSString *imageURL = @"http://www.joinbuy.cn";
+(id)singleOrderDealCellWithDict:(NSDictionary *)dict {
return [[self alloc] initWithDict:dict];
}
-(id)initWithDict:(NSDictionary*)dict{
self = [super init];
if (self) {
self.title = dict[@"name"];
self.currentPrice = [dict[@"unit_price"] floatValue];
self.selledCount = dict[@"number"];
self.imageURL = [NSURL URLWithString:[imageURL stringByAppendingString:dict[@"icon"]]];
}
return self;
}
@end
5.在需要调用的地方
#import "MyOrderDeals.h"
#import "SingleOrderCellDeal.h"
@property(nonatomic,strong) NSMutableArray *myOrders;
-(NSMutableArray *)myOrders{
if (!_myOrders) {
_myOrders = [NSMutableArray array];
}
return _myOrders;
}
//在从服务器导下一组订单数据后
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *dict in array) {
MyOrderDeals *deal = [MyOrderDeals myOrderDealsWithDict:dict];
[self.myOrders addObject:deal];
}
这样一来,从服务器导下来的订单数据,就都解析保存在myOrders这个数组中了,需要什么数据,只要取对应的值就行了。