我需要从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.
}
为了做到这一点,我不知道如何创建这个实例类。它应该是单身吗?如果它不是单身如何创建那个类。
由于
答案 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];
}