Assigning NSDictionary keys to NSStrings - objective-c

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 " " (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);
}

Related

Inserting NSDictionary into sorted NSMutableArray

I want to insert an NSDictionary object into an array and have the array sorted by objectForKey.
I managed to do this by inserting, re-sorting and reloading the array, which works fine, but I figured there would be a better method, which there is, I just don't know how to use it.
Current code:
-(NSMutableArray*)sortArray:(NSMutableArray*)theArray {
return [[theArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"n"
ascending:YES]]] mutableCopy];
}
returns the re-sorted array. Fine. Works perfectly, but... is it the most efficient?
From another question I gather that this is the method to use to find the index to insert into:
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
The problem is I have no idea how to use the comparator method, and if that's even possible when I want to sort by objectForKey for each index.
Can anyone exemplify the above method when the key of the object (newObject in above example) to sort by is, let's say:
[newObject objectForKey:#"sortByThis"];
Use NSSortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sortByThisKey" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
here is the simple example for comparator
- (NSComparisonResult)compareResulst:(CustomObject *)otherObject {
if(self.name isEqualToString:key)
{
return NSOrderedAscending;
}
else
{
return NSOrderedDescending
}
}
NSArray *sArray;
sArray = [unsArray sortedArrayUsingSelector:#selector(compareResulst:)];
this will sort the array. it will iterate through object and based on your if else it will move object up and down ...
Here's an example of sorting
//For make a we're adding 5 random integers into array inform of NSDictionary
//here, we're taking "someKey" to store the integer (converted to string object) into dictionary
NSMutableArray *array = [NSMutableArray array];
for(int i = 1; i<=5; i++) {
[array addObject:[NSDictionary dictionaryWithObject:[#(arc4random()%10) stringValue] forKey:#"someKey"]];
}
//create a sort descriptor to sort the array
//give the key in dictionary for which you want to perform sort
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"someKey" ascending:YES];
//we're doing self sort for mutable array, & that's it, you'll have a sorted array.
[array sortUsingDescriptors:#[sort]];
N.B.
1.Instead of "someKey" from above example you can set any key for which you want to perform sort.
2.There's some other methods for sorting, you can use the one base on your requirement.
3.see #[sort] in code. Its full version is, [NSArray arrayWithObject:sort];

Trouble with simple Array - Cocoa

I was wondering to know if there is any possibility to do the following:
I have a method like:
one = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
two = [[NSMutableArray alloc] initWithObjects:#"4",#"5",#"6", nil];
-(void)getStringAndChooseArray:(NSString *)nameOfArray {
//What i want to do is something like:
NSLog(#"The array %# has got %i objects",nameOfArray,[nameOfArray count])
//Of course it is giving me an error since nameOfArray is a string..
//I know it is hard to understand,
//but what I'm trying to do is to call this method
//pass a string variable, which is named as one of the two arrays,
//and using it to do the rest..
}
How to use a string to identify an array and manipulate it ?
Thanks in advance !
Store your arrays in a dictionary and use the names you want to reference them by as their related keys.
Use a dictionary to map arrays to strings and then you can use them:
one = [[NSMutableArray alloc] initWithObjects:#"1",#"2",#"3", nil];
two = [[NSMutableArray alloc] initWithObjects:#"4",#"5",#"6", nil];
NSDictionary *mapping = [NSDictionary dictionaryWithObjectsAndKeys:#"one",one,#"two",two,nil];
-(void)getStringAndChooseArray:(NSString *)nameOfArray {
NSArray *array = [mapping objectForKey:nameOfArray];
NSLog(#"The array %# has got %i objects",array,[array count])
}

Sort NSMutableArray based on strings from another NSArray

I have an NSArray of strings that I want to use as my sort order:
NSArray *permissionTypes = [NSArray arrayWithObjects:#"Read", #"Write", #"Admin", nil];
I then have a NSMutableArray that may or may not have all three of those permissions types, but sometimes it will only be 2, sometimes 1, but I still want it sorted based on my permissionsTypes array.
NSMutableArray *order = [NSMutableArray arrayWithArray:[permissions allKeys]];
How can I always sort my order array correctly based on my using the permissionTypes array as a key?
I would go about this by creating a struct or an object to hold the permission types.
Then you can have...
PermissionType
--------------
Name: Read
Order: 1
PermissionType
--------------
Name: Write
Order: 2
and so on.
Then you only need the actual array of these objects and you can sort by the order value.
[array sortUsingComparator:^NSComparisonResult(PermissionType *obj1, PermissionType *obj2) {
return [obj1.order compare:obj2.order];
}];
This will order the array by the order field.
NSMutableArray *sortDescriptors = [NSMutableArray array];
for (NSString *type in permissionTypes) {
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:type ascending:YES] autorelease];
[sortDescriptors addObject:descriptor];
}
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
Use whichever sorting method on NSMutableArray you prefer, you will either provide a block or a selector to use for comparing two elements. In that block/selector rather than comparing the two strings passed in directly look each up in your permissionTypes array using indexOfObject: and compare the resulting index values returned.
I suggest you another approuch:
- (void)viewDidLoad
{
[super viewDidLoad];
arrayPermissions = [[NSMutableArray alloc] init];
NSDictionary *dicRead = [NSDictionary dictionaryWithObjectsAndKeys:
#"Read", #"Permission", nil];
NSDictionary *dicWrite = [NSDictionary dictionaryWithObjectsAndKeys:
#"Write", #"Permission", nil];
NSDictionary *dicAdmin = [NSDictionary dictionaryWithObjectsAndKeys:
#"Admin", #"Permission", nil];
NSLog(#"my dicRead = %#", dicRead);
NSLog(#"my dicWrite = %#", dicWrite);
NSLog(#"my dicAdmin = %#", dicAdmin);
[arrayPermissions addObject:dicRead];
[arrayPermissions addObject:dicWrite];
[arrayPermissions addObject:dicAdmin];
NSLog(#"arrayPermissions is: %#", arrayPermissions);
// create a temporary Dict again
NSDictionary *temp =[[NSDictionary alloc]
initWithObjectsAndKeys: arrayPermissions, #"Permission", nil];
// declare one dictionary in header class for global use and called "filteredDict"
self.filteredDict = temp;
self.sortedKeys =[[self.filteredDict allKeys]
sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sortedKeys is: %i", sortedKeys.count);
NSLog(#"sortedKeys is: %#", sortedKeys);
}
hope help

How to extract selected attribute(s) from an NSArray of Core Data entity objects and form into a joint string?

Normally, if I have an NSArray of just NSString's, I can use the NSArray's method:
- (NSString *)componentsJoinedByString:(NSString *)separator
to get a String (like "John,David,Peter"). However, if I have an NSArray of Core Data Entity objects and I just need to to get 1 attribute within (say, the "name" attribute only of each entity object), what is the easiest way to do this?
The Core Data entity object can have many attributes (name, phone, birthdate), but I just want a string like "John,David,Peter".
The following will do a fetch for only the name properties of the Person objects:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Person"];
request.propertiesToFetch = #[#"name"];
request.resultType = NSDictionaryResultType;
NSArray *array = [managedObjectContext executeFetchRequest:request error:nil];
NSString *names = [[array valueForKey:#"name"] componentsJoinedByString:#","];
NSLog(#"%#", names);
You need to set the resultType to NSDictionaryResultType otherwise it will ignore propertiesToFetch. The result from the fetch is an array of Dictionaries. Using valueForKey and componentsJoinedByString will create a single string out of all the names.
Your best option is the straightforward one of building up a NSMutableString by iterating over the items in you array and asking each one for its name to use in appendString:. You could add a description method to the entity object and then use the method you mentioned but description is used for other things and would probably cause conflicts.
// Assuming you have the list of entities - NSArray *entityObjects
NSMutableString *nameAttributes = [[NSMutableString alloc] init];
for(int i = 0; i < [entityObjects count]-1; i++){
[nameAttributes appendString:[NSString stringWithFormat:#"%#, ", [entityObjects objectAtIndex:i].name]];
}
[nameAttributes appendString:[NSString stringWithFormat:#"%#", [entityObjects lastObject].name]];
If you have an NSArray *objects of Core Data objects, each of which has a name attribute, then you can use
NSArray *names = [objects valueForKey:#"name"];
to get a new array with all the names, which you can then concatenate with
NSString *allNames = [names componentsJoinedByString:#","];
You can simply do like that,
NSString *toCollectString =#"";
for(int k =0;k<self.arrayHoldingObjects.count;k++)
{
ModelName *model = [self.arrayHoldingObjects objectAtIndex:k];
NSString *str = model.name;
toCollectString = [toCollectString stringByAppendingString:str];
}
You will get the names in toCollectString.

Getting an NSString out of an NSArray

I am trying to save and read back some application settings stored as NSStrings in an iPhone app and have been having some trouble.
The code to save looks like:
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:accountID];
...
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
And the code to read looks like (accountID is an NSString*):
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
accountID = [array objectAtIndex:0];
...
[array release];
NSLog(#"Loading settings for: %#", accountID);
The read code throws an exception because after the array is released the accountID variable also appears to have been released (moving the NSLog call before releasing the array works fine). So I'm guessing that I'm creating a reference to the array instead of pulling out the actual string contained in the array. I tried several things to create new strings using the array contents but haven't had any luck.
You guess is on the right lines although you have a reference to the 0th element of the array not the array. The array consists of pointers to NSString objects. The Strings will get get released when yhe array is released.
You need to retain the element you are using e/g/
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
NSString* accountID = [[array objectAtIndex:0]retain];
...
[array release];
NSLog(#"Loading settings for: %#", accountID);
When you release the array the reference to the accountID will also be released. You need to retain it.
accountID = [[array objectAtIndex:0] retain];
Then obviously at some point you need to release it.
try [accountID retain] before you release the array