Sort an NSMutableArray alphabetically [duplicate] - ios

This question already has answers here:
How can I sort an NSMutableArray alphabetically?
(7 answers)
Closed 8 years ago.
I have an NSMutableArray with this values:
how, format, anderson, babilon,
I would like to know if there is a command in which you can arrange this array in alphabetical order, so that the end result of the array becomes this:
anderson, babilon, format, how
observation -> my example above 4 items are specified in an array, but actually this array can store more than 1000 items, Someone can help me?

I would like to know if there is a command in which you can arrange
this array in alphabetical order, so that the end result of the array
becomes...
Yes. If you look at the NSMutableArray documentation you'll find a list of methods that can be used for sorting. They all start with the word "sort".
Apple also provides documentation on sorting arrays in the section named Sorting Arrays in Collection Programming Topics. For example, you could use the method -sortUsingSelector: this way:
NSMutableArray *names = [#[#"how", #"anderson", #"format", #"babilon"] mutableCopy];
[names sortUsingSelector:#selector(compare:)];

Related

Sorting an NSArray of Objects by Letter then number [duplicate]

This question already has answers here:
How to do a natural sort on an NSArray?
(5 answers)
Closed 7 years ago.
I have an array of "room" objects, each of these has a property called "room.descritpion" that is an NSString containing a mix of alphanumerical characters. These rooms need to be sorted in an array using the "room.description" property with ascending alphabetical order and then by number order ascending. I can get the alphabetical sorting done easily but I am struggling with how to incorporate the second sort which will be based on the number following the letter e.g. L21 L19
A34 A12 should be ordered in the array as A12, A34, L19, L21 and so on. The priority of the search should be letter first and then by number so a room with only numbers comes at the end of the array. The letters and numbers are not always in the same order i.e. the letter is not always first. I have read the documentation thoroughly but cannot seem to find the way to approach this. I am happy to use blocks if it makes the process easier. Any help would be greatly appreciated.
NSArray *unorderedTitles = [NSArray arrayWithObjects:#"L21",#"L19",#"A34",#"A12",#"A1", nil];
NSArray *orderedTitles = [unorderedTitles sortedArrayUsingSelector:#selector(localizedStandardCompare:)];
NSLog(#"orderedTitles %#",orderedTitles);
Duplicated
This
var arr = ["A6", "A2", "3", "B4", "L8", "4", "B7"]
let sortedArr = arr.sort({String($0) < String($1)})
print(sortedArr)
Will print out
["3", "4", "A2", "A6", "B4", "B7", "L8"]

NSArray find object or objects - best practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Solution:
I have marked #BlackRider's answer as correct as it is the most versatile especially for complex comparisons however there are other very good answers and comments. I would encourage anyone with the same or similar question to review them and evaluate the best course of action for your specific situation.
In my situation, I am actually not using BlackRider's solution in my implementation. I have elected to use my own solution (see Edit #2 below) with help from #JoshCaswell's comments as well as #voromax's suggestion of indexesOfObjectsWithOptions:passingTest: due to the fact that my comparisons are very simple in this situation.
Thanks to everyone who answered and provided insight.
I am looking for an efficient way to retrieve an object from an NSArray based on a property of that object (a unique identifier, in this case). In C#.NET using Linq I would do something like
MyObject obj = myList.Single(o => o.uuid == myUUID);
I am also wondering if there is an efficient way to get an array of objects matching a non-unique property. Again, with Linq it would look like
List<MyObject> objs = myList.Where(o => o.flag == true).ToList();
Of course I can write loops to do this but they would not be reusable and I'm suspicious of their performance.
Finding an object with a unique ID:
-(MyObject*)findObjectWithUUID:(NSString*)searchUUID{
for (MyObject* obj in _myArray){
if([obj.uuid isEqualToString: searchUUID])
return obj;
}
}
Finding an array of objects:
-(NSArray*)findObjectsWithFlag:(BOOL)f{
NSMutableArray* arr = [NSMutableArray array];
for (MyObject* obj in _myArray){
if(obj.flag == f)
[arr addObject:obj];
}
return arr;
}
-- EDIT --
Luckily in the first situation the object I am looking for has a unique identifier and I know there will only be one. I came up with a solution to implement isEqual on my object which will be invoked by indexOfObject:
- (BOOL)isEqual:(id)object{
return [self.uuid isEqualToString: ((MyObject*)object).uuid];
}
And then create a "fake" lookup object and use that to find the real one
MyObject *lookupObject = [[MyObject alloc] init];
lookupObject.uuid = searchUUID;
MyObject *actualObject =
[_myArray objectAtIndex:[_myArray indexOfObject:lookupObject]];
This is essentially the same as the for-in loop I posted above, but might be more readable & be more reusable. Of course, this only works for finding one unique object and does not address the second half of my question.
-- EDIT 2 --
Checking Class and implementing hash as recommended in comments.
- (BOOL)isEqual:(id)object{
return [object isKindOfClass:[MyObject class]] &&
[self.uuid isEqualToString: ((MyObject*)object).uuid];
}
- (NSUInteger)hash{
return [self.uuid hash];
}
You can use [NSPredicate], which gives you a query-like syntax for search. Check out this page for the predicate syntax description. Here's a simple example:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"propertyName == %#", #"value"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
As to performance, I think your solution is OK since any search in an array needs to iterate through all the elements anyway, and then, for each object, compare the value of a field against the value you search for. You can optimize repeat searches within the same data, e.g. by creating and populating a dictionary that maps values of some field to the matching objects (or collections of objects, if the mapping is one to many).
You may also look at modern block syntax: indexOfObjectWithOptions:passingTest: or indexesOfObjectsWithOptions:passingTest: which support concurrency and search order.
I was intrigued by rmaddys comment so I've checked the difference between looping and predicate.
Let's assume a simple object with NSString property. I've inserted it into array 10 000 times , every time with different property value.
In the worst case scenario when desired object was on the last position of the array, loop approach was 3.5x faster than NSPredicate (0.39s vs 0.11s, arraySize = 10000, 10 iterations, iPad Mini)
Code I used for reference: pastebin
I know its related with NSArray but if we do it using Swift and using the swift Array which is a struct, then that will be lot easier.
Swift 2.2 / Swift 3.0 / Swift 4.x Working fine on all versions
Lets assume we have a custom model class
class User {
var userId = 0
var userName = ""
}
And lets assume we have an array named as usersArray which has custom objects of User class.
And we want to fetch an object from this array with userId = 100 for example:-
let filteredArray = usersArray.filter({$0.userId == 100})
This filtered array will contain all the custom objects which have userId as 100
print(filteredArray[0].userName) //will print the name of the user with userId = 100
just for those who are interested, I've found the fastest way to search through NSArray is by using a for loop on a background thread. using the [self performSelectorInBackground...] method.
In an NSArray of 10000 custom objects I searched through the whole thing thoroughly in around 1 second. On the main thread it took around 10 seconds or more.

How to efficiently extract matching objects from an NSArray? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
I'm looking for the most efficient way to achieve the following task...
I have an array of Objects of type Foo, amongst other properties, Foo has a latitude and a longitude property. Given an array of many Foo's, I need to extract the Foo's with matching lat / long's into one new array.
I have implemented several solutions which are working, including iterating using a for loop, and a solution using an NSPredicate, but both of these methods involve multiple iterations through an array. This array could potentially have hundreds of thousands of records, so i'm looking for something i can use which will achieve the desired result in one pass.
EDIT: Adding some pseudo-code to describe the approach i've already taken and to better describe the problem...
NSMutableArray * matchingLocations = [[NSMutableArray alloc] initWithCapacity:0];
for (Foo * checkingFoo in fooArray) {
NSMutableArray * checkingArray = [NSArray arrayWithArray:fooArray];
[checkingArray removeObject:checkingFoo];
for (Foo * foo in checkingArray) {
// I have a method coded for comparing two coordinates
if (checkingFoo.coordinate == foo.coordinate) {
[matchingLocations addObject:checkingFoo];
}
}
}
NSSet will provide a collection of unique objects. In order to implement it properly however you need to define what does mean to be identical for the Foo object. You do that in your Foo class implementation rewriting the method isEqual: and the method hash.
In your Foo class:
- (BOOL)isEqual:(id)object {
return (self.coordinate == [(Foo *)object coordinate]);
}
- (NSUInteger)hash {
return ([self.coordinate hash]);
}
Then everywhere in your code you can just use:
NSArray *array; // Your array with multiple Foo objects potentiually duplicates
NSSet *set = [NSSet setWithArray:array];
Have a loo kat the Apple Documentation reference for:
[NSObject isEqual:] https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/isEqual:
[NSSet setWithArray:]
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSSet_Class/Reference/Reference.html#//apple_ref/occ/clm/NSSet/setWithArray:
You are running two fast enumeration as for loop of same array. Which is not correct. If you want to compare the co-ordinates then excecute for loop of different array. And also you can add directly to mutable array if same for loop only you are using.
If you want to compare objects from the array, then I suggest you use NSSet instead of NSArray.
It is very easy to use and the below link is something you want because I resolved such a case using NSMutableSet :
NSSet Tutorial

Sort multiple arrays

Here is my situation:
I manipulate 6 NSMutableArrays. One of them has NSDates objects in it, the other ones have NSNumbers. When I populate them, I use addObject: for each of them, so index 0 of each array contains all the values I want for my date at index 0 in the dates array.
I want to make sure that the arrays are all sorted according to the dates array (order by date, ascending), meaning that during the sorting, if row 5 of the dates array is moved to row 1, it has to be applied to all the other arrays as well.
I was previously using CoreData, but I must not use it anymore (please don't ask why, this is off-topic ;) ). In CoreData, I could use an NSSortDescriptor, but I have no idea on how to do it with multiple NSArrays...
As always, hints/answers/solutions are always appreciated :)
This is a common problem. Use the following approach.
Encapsulate your six arrays into an object - every instance will have six properties.
Implement compare: method on this object, using [NSDate compare:] (this step can be skipped but it's cleaner this way).
Now you have only one array - sort it using the method from step 2.
I think the better solution for you to have NSArray of NSDictionary objects.
NSArray *allValues = [[NSArray alloc] init];
NSDictionary *dict = #{"Date" : [NSDate date], #"Key1" : #"Value1", #"Key2" : #"Value2"};
Then you can sort this array with sortDescriptor without any problems.
And then you can also use Comparator or Sort Desriptor as you wish.
Wrap all your items that you are storing in an array into a single object. Each one of your previous 6 arrays will be a property.
Inside that object you can implement
- (NSComparisonResult)compare:(YourClass *)otherObject {
return [self.date compare:otherObject.date];
}
You can now sort the array and they will sort by date.

Order two NSMutableArrays based on one

I have two NSMutableArrays. The content of the first is numerically, which is paired to the content of the second one:
First Array Second Array
45 Test45
3 Test3
1 Test1
10 Test10
20 Test20
That's the look of both arrays. Now how could I order them so numerically so they end up like:
First Array Second Array
1 Test1
3 Test3
10 Test10
20 Test20
45 Test45
Thanks!
I would put the two arrays into a dictionary as keys and values. Then you can sort the first array (acting as keys in the dictionary) and quickly access the dictionary's values in the same order. Note that this will only work if the objects in the first array support NSCopying because that's how NSDictionary works.
The following code should do it. It's actually quite short because NSDictionary offers some nice convenience methods.
// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
Rather than keep two parallel arrays, I'd keep a single array of model objects. Each number from the first array would be the value of one property, and each string from the second array would be the value of the other property. You could then sort on either or both properties using sort descriptors.
Generally, in Cocoa and Cocoa Touch, parallel arrays make work while model objects save work. Prefer the latter over the former wherever you can.

Resources