开发者

Loading a series of positionally defined file records into a class

开发者 https://www.devze.com 2023-02-13 08:02 出处:网络
As you will be able to see shortly, I\'m pretty new to objective-c and need a little help. I\'m attempting to read a file that has a series of fixed length records on it (downloaded from a mainframe)

As you will be able to see shortly, I'm pretty new to objective-c and need a little help.

I'm attempting to read a file that has a series of fixed length records on it (downloaded from a mainframe) and load each entry into a class instance and then add that class instance into an array. Let's call that class CLASS_A. I have a second class, CLASS_B which I have wrapped around the input file which has one method to read the file into a NSString, a second method advances to the next record in the file (moves a pointer just past the next '\n') and other methods are used to extract individual data fields into returned NSString values. There are also some other imbedded checks to make sure that each field fetch does not reach beyond the current record. Probably a bit fussy but since this is a demonstration program, I don't care much.

I declared several instances of CLASS_A and loaded each instance of CLASS_A using the methods defined for CLASS_B and then loaded these CLASS_A instances into an array successfully. Fine. I can see them in the debugger and can fetch them using the various array methods which do that.

Now I want to generalize this thing so I can set up a loop and just merrily fill up CLASS_A table with one CLASS_A entry per input file record accessed via the various methods in CLASS_B until I run out of input records. In my working example I explicitly named about 5 or so CLASS_A instances and added them into the array. How do I get away from explicitly naming the CLASS_A instances and just 开发者_C百科loop around. I really don't care what the names of the individual CLASS_A instances are... they exist to be bundled into the table and fetched out as required by other parts of the program.

Any help would be great. The code is a bit longish for this site but if it is helpful I can post it as well.


A classic way to do this is to have a class method (the ones which start with a +) which takes in the data, and hands over a populated instance.

+ (CLASS_A *) class_aFromStringArray: (NSArray *)stringArray {
   CLASS_A *myInstance = [[CLASS_A alloc] init];

   //Populate myInstance ivars here from stringArray

   [myInstance autorelease];
   return myInstance;
}

In your other class, you'd have your loop do something like

   while (FileNotEOF) {
     peel off a line;
     parse line into (NSMutableArray *) aMutableArray;
     [myClass_AArray addObject: [CLASS_A class_aFromStringArray: aMutableArray]];
}
0

精彩评论

暂无评论...
验证码 换一张
取 消