如何在iOS中创建NSObject类

use*_*249 1 nsobject ios7

我需要从Web服务中获取大量数据,它有一种JSON格式.所以我创建了一个NSObject类来分配每个对象的属性.我想将这些JSON数据放入a 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.

 }
Run Code Online (Sandbox Code Playgroud)

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

谢谢

tro*_*foe 6

不,它不应该是单身人士.您应该NSObject像任何其他对象一样创建您的-derived类:

MyCustomClass *myClass = [MyCustomClass new];
Run Code Online (Sandbox Code Playgroud)

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

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];
}
Run Code Online (Sandbox Code Playgroud)

所以你的自定义类可以像下面这样简单:

@interface MyCustomClass : NSObject

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

@end
Run Code Online (Sandbox Code Playgroud)

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

@interface MyCustomClass : NSObject

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

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

@end
Run Code Online (Sandbox Code Playgroud)

使用这样的转换方法:

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