开发者

Assigning NSDictionary keys to NSStrings

I'm importing a txt file with a list of first and last names. Each new name is on it's own line, so I imported them into a NSMutableArray and then split them with componentsSeparatedByString:@"\n". I then want to sort the names via their last name. I have found this Sort collections, but I'm lost at how I would tell my NSStrings that are within my Array to have the key's firstName and lastName. Obviously I'd have to make an NSDictionary, but can you do a for loop where by I say something like anything before the 开发者_如何学Python" " (space) is firstName, and anything after is the lastName.

Hopefully I've been clear enough,

Thanks in advance.

EDIT: This is all going to be displayed in a UITableView, if that changes/helps.


Personally, I would make a simple class called Name that has a property for firstName and a property for lastName. You can then loop through the array and to create your Name instances, add them to an NSMutableArray and then sort the array. You can go the dictionary route if you want of course.

Here is an example:

NSMutableArray *namesList = [NSMutableArray arrayWithCapacity:0];

for (NSString *name in originalArray) {
  NSArray *tempArray = [name componentsSeparatedByString:@" "];
  Name *newNameInstance = [[Name alloc] init];
  newNameInstance.firstName = [tempArray objectAtIndex:0];
  newNameInstance.lastName = [tempArray objectAtIndex:1];
  [namesList addObject:newNameInstance];
}

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"lastName"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [namesList sortedArrayUsingDescriptors:sortDescriptors];

This code hasn't been checked but it should work. I haven't taken care with memory management so please be mindful of that.

Update Sorry, should be [tempArray objectAtIndex:0]. Fixed it above.

Since firstName and lastName are strings then they should be declared as NSString. Try not to use id for a property unless you have a really good reason.

Update 2 If you want to check the values do this:

for (Name *name in sortedArray) {
   NSLog(@"%@", name.firstname);
   NSLog(@"%@", name.lastName);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜