2013-02-14 4 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 문자열을 읽어와 이미지 모델 생성 : 것 그리고 imagesCollection.images의 각 요소를

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

ImageModel 인스턴스.

Voila!

+0

"initWithDictionary"를 실행하고 Json 응답에 사전 배열이있는 경우 JSONModelError "initWithDictionary를 사용하여 JSONModel 개체를 초기화하려고합니다. 오류 :하지만 사전 매개 변수가 initWithDictionary 모델에서 'NSDictionary'가 아닙니다. –