2011-08-07 153 views
7

我試圖將以下JSON的關係映射到CoreData支持的模型。與RestKit嵌套的多對多關係

這裏的JSON:我已經與RestKit的OM2類映射

{ 
    "photos": [ 
     { 
      "id": 1, 
      "thumb": "http://localhost/test_1_thumb.png", 
      "image": "http://localhost/test_1.png", 
      "date": "2011-07-02T06:06:16Z", 
      "likes": 0, 
      "user": { 
       "id": 1, 
       "username": "User1", 
       "avatar": "http://cdn.domain.com/avatar.jpg" 
      }, 
      "comments": [ 
       { 
        "date": "2011-07-02T06:06:16Z", 
        "text": "This is the only comment", 
        "id": 1, 
        "author": { 
         "username": "User1", 
         "id": 1, 
         "avatar": "http://cdn.domain.com/avatar.jpg" 
        } 
       } 
      ] 
     } 
    ] 
} 

我CoreData模型。

CoreData Entities

的照片類。

@interface Photo : NSManagedObject 

@property (nonatomic, retain) NSString * thumbnailUrl; 
@property (nonatomic, retain) NSString * imageUrl; 
@property (nonatomic, retain) NSDate * date; 
@property (nonatomic, retain) NSNumber * likes; 
@property (nonatomic, retain) NSNumber * photoID; 
@property (nonatomic, retain) User *owner; 
@property (nonatomic, retain) NSSet *comments; 

@end 

@interface Photo (CoreDataGeneratedAccessors) 

- (void)addCommentsObject:(Comment *)value; 
- (void)removeCommentsObject:(Comment *)value; 
- (void)addComments:(NSSet *)values; 
- (void)removeComments:(NSSet *)values; 

@end 

@implementation Photo 

@dynamic thumbnailUrl; 
@dynamic imageUrl; 
@dynamic date; 
@dynamic likes; 
@dynamic photoID; 
@dynamic owner; 
@dynamic comments; 

@end 

現在我不是完全確定的部分是關係:

// Map relationships between entities. 
[commentMapping mapKeyPath:@"author" toRelationship:@"author" withMapping:userMapping]; 
[photoMapping mapKeyPath:@"user" toRelationship:@"owner" withMapping:userMapping]; 
[photoMapping mapKeyPath:@"comments" toRelationship:@"comments" withMapping:commentMapping]; 

有了這個,我能夠訪問所有,但照片的comments屬性,與此錯誤:Comments = Relationship 'comments' fault on managed object 。我有一種感覺,這是與被定義爲NSSet的comments的照片模型有關,或者我在關係映射中做了一些錯誤,但我不確定。

回答

7

所以原來,問題是無關RestKit或映射,但我怎麼CoreData功能的理解。

我在我的delgate訪問映射的JSON對象如下:

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects { 
    NSLog(@"Loaded photos: %@", objects); 

    for (id object in objects) { 
     Photo *photo = object; 
     // Print other photo attributes... 

     NSLog(@"Comments = %@", photo.comments); 
    } 
} 

的問題是在試圖直接打印集合對象。 CoreData不會觸發數據存儲上的錯誤。簡單地用下面的快速迭代代替,並訪問屬性允許我訪問評論對象。

for (Photo *photo in objects) { 
    for (Comment *comment in photo.comments) NSLog(@"Comment = %@", comment.text); 
} 
+0

你救了我,非常感謝! –