2012-04-24 5 views
6

중첩 배열 매핑에 대한 질문이 있습니다. https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md에는 중첩 된 객체를 매핑하는 예제가 있습니다.Restkit 매핑 중첩 배열

{ "articles": [ 
    { "title": "RestKit Object Mapping Intro", 
     "body": "This article details how to use RestKit object mapping...", 
     "author": [{ 
      "name": "Blake Watters", 
      "email": "[email protected]" 
     }, 
     { 
      "name": "abc", 
      "email": "emailaddress" 
     }] 
     "publication_date": "7/4/2011" 
    }] 
} 

어떻게 내 수업은 저자의 배열을 얻기를 위해, 같이한다 : 중첩 된 개체가 JSON의 모습 예를 들어 객체의 배열 인 경우

하지만, 무엇을해야합니까? 예제의 코드 그게 :

@interface Author : NSObject 
    @property (nonatomic, retain) NSString* name; 
    @property (nonatomic, retain) NSString* email; 
@end 



@interface Article : NSObject 
    @property (nonatomic, retain) NSString* title; 
    @property (nonatomic, retain) NSString* body; 
    @property (nonatomic, retain) Author* author; // should be an array of Author-Objects 
    @property (nonatomic, retain) NSDate* publicationDate; 
@end 

나는 저자의 배열을 프로그래머 내가있는 NSArray에 문서의 저자 속성의 클래스를 변경하고 있다면, 어떻게하는지 Restkit가에 그, 알고 Restkit를 알 수있는 방법 이 NSArray는 Author-Objects 여야합니다 ... ??

저는 RKObjectMapping을 사용하여 Object를 JSON에서 Objective-c로 또는 그 반대로 매핑합니다.

답변

0

전체 respnse 문자열은 .. 다음은 저자 값 배열을 namutable에 할당 nsmutable 사전으로 가져

당신은 그에 따라 VAR 유형 설정 확인 할 수 있습니다
7

:

@interface Article : NSObject 
    @property (nonatomic, retain) NSString* title; 
    @property (nonatomic, retain) NSString* body; 
    @property (nonatomic, retain) NSSet* authors; 
    @property (nonatomic, retain) NSDate* publicationDate; 
@end 

그것은 월 그것을 NSArray로 선언하고 작업하지만 저는 개인적으로 CoreData 모델과 함께 RestKit을 사용합니다. 이러한 시나리오의 관계는 NSSet입니다.

또한 매핑을 설정해야합니다

[articleMapping mapKeyPath:@"author" toRelationship:@"authors" withMapping:authorMapping]; 
3

분할 그것을 밖으로는 데 도움이됩니다.

@interface Author : NSObject 
    @property (nonatomic, retain) NSString* name; 
    @property (nonatomic, retain) NSString* email; 
@end 



@interface Article : NSObject 
    @property (nonatomic, retain) NSString* title; 
    @property (nonatomic, retain) NSString* body; 
    @property (nonatomic, retain) NSArray* author; 
    @property (nonatomic, retain) NSDate* publicationDate; 
@end 


//create the article mapping 
RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]]; 
//add rest of mappings here 
[articleMapping addAttributeMappingsFromDictionary:@{ 
                @"title":@"title" 
} 

//create the author mapping 
RKObjectMapping *authorMapping = [RKObjectMapping mappingForClass:[Author class]]; 
//add rest of mappings here 
[authorMapping addAttributeMappingsFromDictionary:@{ 
                @"name":@"name" 
} 

//link mapping with a relationship 
RKRelationshipMapping *rel = [RKRelationshipMapping relationshipMappingFromKeyPath:@"authors" toKeyPath:@"author" withMapping:authorMapping]; 

//add relationship mapping to article 
[articleMapping addPropertyMapping:rel];