Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In terms of the CSV parsing, assuming you can spend the memory it's probably easiest to read in the whole thing to an <code>NSString</code>, split that on newlines and then split each line on commas, essentially as PLPiper suggests.</p> <p>At that point I'd take a detour into key-value coding. Give your columns in the CSV file exactly the same name as the properties on your runtime object. Then you can just write something like:</p> <pre><code>// this method will create an object of the given type then push the values // from valueRow to the properties named by headingRow. So, ordinarily, // headingRow will be the first row in your CSV, valueRow will be any other - (id)populatedObjectOfType:(Class)type withHeadingRow:(NSArray *)headingRow valueRow:(NSArray *)valueRow { // we need the count of fields named in the heading row to // match the count of fields given in this value row if([headingRow count] != [valueRow count]) return nil; // autorelease if you're not using ARC id &lt;NSObject&gt; newInstance = [[type alloc] init]; // we need to enumerate two things simultaneously, so // we can fast enumerate one but not the other. We'll // use good old NSEnumerator for the other NSEnumerator *valueEnumerator = [valueRow objectEnumerator]; for(NSString *propertyName in headingRow) { [newInstance setValue:[valueEnumerator nextObject] forKey:propertyName]; } return newInstance; } ... elsewhere .... CargoShip *newShip = [self populateObjectOfType:[CargoShip class] withHeadingRow:[csvFile objectAtIndex:0] valueFor:[csvFile objectAtIndex:1]]; </code></pre> <p>The main caveat is that the built-in mechanisms will convert between scalars and objects but not between objects of different types. So if you had all <code>NSString</code> and C integer types (<code>short</code>, <code>int</code>, <code>NSUInteger</code>, etc) you'd be fine, but if you had some <code>NSString</code>s and, say, some <code>NSNumber</code>s then you would end up with strings stored in the number slots. It looks like you're using C integer types (as is quite normal) so you should be fine.</p> <p>In terms of filtering, you can use <code>NSPredicate</code>s. For example, suppose you had an array of <code>CargoShip</code>s and wanted every one with a <code>size</code> of at least 500:</p> <pre><code>NSArray *bigShips = [allShips filteredArrayUsingPredicate: [NSPredicate predicateWithFormat:@"size &gt; 500"]]; </code></pre> <p>Similarly, for sorting you can throw some <code>NSSortDescriptor</code>s at the problem. E.g.</p> <pre><code>NSArray *shipsSortedBySize = [allShips sortedArrayUsingDescriptors: @[[NSSortDescriptor sortDescriptorWithKey:@"size" ascending:YES]]]; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload