【问题标题】:IOS/Objective-C: Error Converting JSON to ObjectIOS/Objective-C:将 JSON 转换为对象时出错
【发布时间】:2015-10-18 16:45:58
【问题描述】:

我正在尝试将 JSON 数组转换为对象以在表格中显示。我能够捕获 JSON。但是,当我尝试变成对象时,出现如下所示的错误。在对象类中肯定有一个名为“name”的属性。

- (void)fetchedData:(NSData *)responseData {
    NSError* error;
    NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData 
                                                         options:kNilOptions
                                                           error:&error];
    NSMutableArray* latestItems = nil;
    latestItems = [[NSMutableArray alloc] init];
    latestItems = [json objectForKey:@"items"];
    [self.tableView reloadData];
    for (int i = 0; i < latestItems.count; i++)
    {
        NSDictionary *itemElement = latestItems[i];
        // Create a new l object and set its props to todoElement properties
        IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
//ERROR  NEXT LINE THROWS FOLLOWING ERROR
//'NSUnknownKeyException', reason: '[<IDItemFromServer 0x14e88010> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
       [newItem setValue:@"hi" forKey:@"name"];
       [newItem setValue:itemElement[@"address"] forKey:@"address"];

        // Add this new item  to the array
        [latestItems addObject:newItem];
    }

如果有任何关于如何修复错误的建议,我们将不胜感激。

编辑:

//Object.h file
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface IDItemFromServer : NSObject
@property (nonatomic, retain) NSNumber * iid;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * address;

@end

【问题讨论】:

  • 该错误表明没有名为name 的属性。使用有关IDItemFromServer 类接口的详细信息更新您的问题。
  • 如果您有一个不错的公共财产,为什么不直接使用newItem.name = @"hi"; 而不是使用setValue:forKey:
  • 我之前尝试过这个,它给了我 //[IDItemFromServer setName:]: unrecognized selector sent to instance 0x16d7dfd0 错误,但是,我会再试一次。
  • 是的,它正在抛出 IDItemFromServer setName:]: unrecognized selector sent to instance 0x15599ed0' that way
  • 当属性在运行时而不是编译时合成时,您只需要@dynamic

标签: ios json kvc


【解决方案1】:

它说 IDItemFromServer 没有属性 name。添加 name,address 属性,如以下代码

In IDItemFromServer.h file

#import <Foundation/Foundation.h>
@interface IDItemFromServer : NSObject

@property(nonatomic,strong) NSString name;
@property(nonatomic,strong) NSString address;

@end

在 IDItemFromServer.m 文件中

#import "IDItemFromServer.h"

@implementation IDItemFromServer

@synthesize name;
@synthesize address;

@end

【讨论】:

  • 1) 该问题显示了IDItemFromServer 的接口,并且它确实具有name 属性。 2) 你为什么打电话给@synthesize?这几年都不需要了。
  • 感谢您关注 .m 文件。
猜你喜欢
  • 2011-11-27
  • 2018-12-15
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多