Re: Reading cab into object
Re: Reading cab into object
- Subject: Re: Reading cab into object
- From: Marcel Weiher <email@hidden>
- Date: Sat, 4 Apr 2009 14:01:23 -0700
On Apr 3, 2009, at 14:18 , Mark Bateman wrote:
Hi
I have a csv file I want to use as a source for a searchable list
The csv has 16 fields. I have managed to read the csv line by line
into an array
You don't necessarily need to read the lines into an array, you can
just process them one-by-one.
I'm having difficulty figuring out how to load an instance of an
object with the single line of the array and initialising each of
the objects properties with the fields seperated by commas
What am I missing. Should I load an intermediate array using
ComponentsSeparatedByString method. Even so how do I then initialize
the custom object fields
-componentsSeparatedByString: is a reasonable way of getting the
components. You will then have 16 individual strings.
The rest depends very much on your actual class and on the values,
here is an example with 4 fields
#import <Foundation/Foundation.h>
@interface MyObject : NSObject
{
id a,b;
int c,d;
}
@end
@implementation MyObject
-initWithCSV:(NSString*)csvString
{
self=[super init];
if (self) {
id fields=[csvString componentsSeparatedByString:@","];
a=[[fields objectAtIndex:0] retain];
b=[[fields objectAtIndex:1] retain];
c=[[fields objectAtIndex:2] intValue];
d=[[fields objectAtIndex:3] intValue];
}
return self;
}
-description { return [NSString stringWithFormat:@"<%@:%p a=%@ b=%@ c=
%d d=%d",[self class],self,a,b,c,d]; }
@end
int main( int argc, char *argv[] )
{
id pool=[NSAutoreleasePool new];
char buffer[1024];
NSMutableArray *arrayOfObjects=[NSMutableArray array];
while ( fgets(buffer,1000, stdin) ) {
if ( strlen(buffer) > 1 ) {
buffer[strlen(buffer)-1]=0;
}
[arrayOfObjects addObject:[[[MyObject alloc] initWithCSV:[NSString
stringWithCString:buffer]] autorelease]];
}
NSLog(@"array: %@",arrayOfObjects);
exit(0);
[pool release];
return 0;
}
------------------------------------------------
marcel@spock[tmp]./a.out
hello world, cocoa rocks, 1 ,2
according to douglas adams, the answer is, 42, 0
^D
2009-04-04 14:00:49.229 a.out[69819:10b] array: (
<MyObject:0x1059b0 a=hello world b= cocoa rocks c=1 d=2,
<MyObject:0x106c10 a=according to douglas adams b= the answer is
c=42 d=0
)
marcel@spock[tmp]
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden