我想使用RestKit的RKObjectManager將JSON數據反序列化到我的iPhone應用程序。獲取「這個類不是密鑰編碼兼容的密鑰ID」。當請求RestKit loadObjectsAtResourcePath
我現在的問題是,應用程序崩潰了:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Course 0x6e71b10> valueForUndefinedKey:]: this class is not key value coding-compliant for the key id.'
當我打電話:
[manager loadObjectsAtResourcePath:@"/courses" delegate:nil];
我的領域類 - Course.h看起來像
#import <Foundation/Foundation.h>
@interface Course : NSObject {
}
@property(nonatomic) NSInteger *id;
@property(nonatomic, retain) NSString *name;
-(id)initWithIdAndName: (NSInteger *)inId inName:(NSString *)inName;
@end
和Course.m看起來像
#import "Course.h"
#import "NSDictionary+RKAdditions.h"
@implementation Course {
}
@synthesize name = _name;
@synthesize id = _id;
- (id)initWithIdAndName:(NSInteger *)inId inName:(NSString *)inName {
_name = inName;
_id = inId;
return self;
}
#pragma mark NSCoding Protocol
- (void)encodeWithCoder:(NSCoder *)encoder;
{
[encoder encodeInteger:[self id] forKey:@"id"];
[encoder encodeObject:[self name] forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)decoder;
{
if (![super init])
return nil;
[self setId:[decoder decodeIntForKey:@"id"]];
[self setName:[decoder decodeObjectForKey:@"name"]];
return self;
}
@end
個
從服務器檢索的JSON數據是
{"courses":[{"id":1,"name":"course 1"},{"id":2,"name":"course 2"}]}
而且RKObjectManager使用如下代碼調用:
RKObjectMapping* courseMapping = [RKObjectMapping mappingForClass:[Course class]];
[courseMapping mapKeyPath:@"id" toAttribute:@"id"];
[courseMapping mapKeyPath:@"name" toAttribute:@"name"];
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:@"http://firstbit/of/url"];
[manager.mappingProvider setMapping:courseMapping forKeyPath:@"courses"];
[manager loadObjectsAtResourcePath:@"/endpoint" delegate:nil];
在這一個任何想法?
也許你可以嘗試改變id屬性爲類似courseId,以避免可能的命名衝突。 – mja 2012-01-15 22:27:22
我不認爲這是問題,但應該是NSInteger,而不是NSInteger *反正:http://stackoverflow.com/questions/1014053/why-dont-i-declare-nsinteger-with-a – pshah 2012-11-06 19:20:22