2013-02-14 135 views
4

我有一個問題,通過JSONModel libraryJSONModel不良屬性協議聲明?

{"images":[{"id":1,"name":"name1","img":"3423","note":"note1"},{"id":2,"name":"name2","img":"rew","note":"note2"},{"id":3,"name":"name3","img":"dsfs","note":"note3"},{"id":4,"name":"name4","img":"cxvxc","note":"note4"},{"id":5,"name":"name5","img":"erwe","note":"note5"}]} 

閱讀JSON類模型

#import "JSONModel.h" 

@protocol ImagesModel @end 

@interface ImagesModel : JSONModel 
@property int id; 
@property (strong, nonatomic) NSString* name; 
@property (strong, nonatomic) UIImage* img; 
@property (strong, nonatomic) NSString* note; 
@end 

,我得到這個錯誤

Terminating app due to uncaught exception 'Bad property protocol declaration', reason: '<ImagesModel> is not allowed JSONModel property protocol, and not a JSONModel class.' 

任何幫助嗎?

回答

4

我可以看到兩個問題,你

你的模式是很好的粘貼代碼,但它是一個項目的模型 - 即。這是您將要用來加載單個圖像的模型 - 並不是所有的圖像一次。因此,您需要一個模型來描述您擁有一組圖像,以及另一個模型(您擁有該模型)來描述每個圖像對象。

第二個問題是您的其中一個屬性是UIImage對象,但是您在JSON提要中傳遞字符串。

因此有你的榜樣工作,你需要:

#import "JSONModel.h" 

//define the single image object protocol 
@protocol ImageModel @end 

//define the single image model 
@interface ImageModel : JSONModel 
@property int id; 
@property (strong, nonatomic) NSString* name; 
@property (strong, nonatomic) NSString* img; 
@property (strong, nonatomic) NSString* note; 
@end 

@implementation ImageModel 
@end 

//define the top-level model for the collection of images 
@interface Images : JSONModel 
@property (strong, nonatomic) NSArray<ImageModel>* images; 
@end 

,然後讀你的JSON字符串,並創建一個圖片模型:

NSError* err = nil; 
Images* imagesCollection = [[Images alloc] initWithString:JSONstring error:&err]; 

然後每個imagesCollection.images元素會一個ImageModel實例。

瞧!

+0

當我們執行「initWithDictionary」並且Json響應有一個字典數組時,它返回一個JSONModelError「嘗試使用initWithDictionary初始化JSONModel對象:錯誤:但字典參數不是'initDithDictionary模型中的'NSDictionary'」。 – 2015-08-14 13:52:42