如何在iOS中创建NSObject类

时间:2014-03-18 08:02:10

标签: ios7 nsobject

我需要从Web服务获取大量数据,它具有JSON格式。所以我创建了一个NSObject类来分配每个对象的属性。我想将JSON数据放入NSMutableArray,然后使用for循环。使用这些新对象数组后,我想填充UITableView

`

 for(int i=0;i<[matubleArray count];i++)
 {
  //create a new instance from the class
  //assign each values from mutable array to new object's properties
  //add that new object to another mutable array.

 }

为了做到这一点,我不知道如何创建这个实例类。它应该是单身吗?如果它不是单身如何创建那个类。

由于

1 个答案:

答案 0 :(得分:6)

不,它不应该是单身人士。您应该像任何其他对象一样创建NSObject派生类:

MyCustomClass *myClass = [MyCustomClass new];

然后从JSON数据开始填充它(通过@property访问器)(这假设一个字典对象数组,这并不罕见):

for (unsigned i = 0; i < [jsonData count]; i++)
{
    MyCustomClass *myClass = [MyCustomClass new];
    NSDictionary *dict = [jsonData objectAtIndex:i];
    myClass.name = [dict objectForValue:@"Name"];
    myClass.age = [[dict objectForValue:"@"Age"] unsignedValue];
    [someOtherArray addObject:myClass];
}

因此,您的自定义类可以像以下一样简单:

@interface MyCustomClass : NSObject

@property (strong, nonatomic) NSString *name;
@property (assign, nonatomic) unsigned age;

@end

当然,在保存更复杂的对象(如日期)时,事情变得有趣,您应该使用NSDate对象来保存这些对象并提供字符串到日期的转换方法:

@interface MyCustomClass : NSObject

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSDate *dateOfBirth;

- (void)setDateOfBirthFromString:(NSString *)str;

@end

转换方法如下:

- (void)setDateOfBirthFromString:(NSString *)str {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    self.dateOfBirth = [dateFormat dateFromString:str]; 
}