Domanda

I need to get some large amount of data from a web service,, It has a JSON format. so I created a NSObject class to assign every object's properties. Im thinking to get that JSON data into a NSMutableArray and then using a for loop.After using these new object array I want to fill an 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.

 }

in order to do this, I don't know how to create this instance class. Is it should be singleton? If its not singleton how to create that class.

Thanks

È stato utile?

Soluzione

No it should not be a singleton. You should create your NSObject-derived class like any other object:

MyCustomClass *myClass = [MyCustomClass new];

and then start populating it (via @property accessors) from the JSON data (this assumes an array of dictionary objects, which is not uncommon):

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];
}

So your custom class can be as simple as:

@interface MyCustomClass : NSObject

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

@end

Of course things get interesting when holding more complex objects like dates, and you should use an NSDate object to hold these and provide a string-to-date conversion method:

@interface MyCustomClass : NSObject

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

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

@end

With the conversion method something like this:

- (void)setDateOfBirthFromString:(NSString *)str {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    self.dateOfBirth = [dateFormat dateFromString:str]; 
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top