Sort NSMutableArray Of multiple Objects without keys - objective-c

I have a NSMutableArray of objects, below is the struct:
//object at index i
locations {
NSString* address;
NSString* state;
NSNumber* distance;
}
I have 10000 object like the above structure in the NSMutableArray.
How do order this array so that the locations are in order by the NSNumber distance?
I tried this:
lowToHigh = [NSSortDescriptor sortDescriptorWithKey:#"distance" ascending:YES];
[locationArray sortUsingDescriptors:[NSArray arrayWithObject:lowToHigh]];
is using the sortDescriptorWithKey:#"distance" wrong? since distance isn't actually a key, it NSNumber* distance.
edit in my header #property (strong, nonatomic)NSNumber* _distance; and then #synthesize _distance = distance; in my methods file but this is in locationObjects.* object class. Then I import this in my current class I am doing this sorting. Is that an issue?
How I import is locationObjects* locObj = [[locationObjects alloc] init];

This is what I use:
NSSortDescriptor *lowToHigh = [[NSSortDescriptor alloc] initWithKey:#"distance"
ascending:YES];
NSArray *mySortDescriptors = [NSArray arrayWithObject:lowToHigh];
NSArray *sortedArray = [locationArray sortedArrayUsingDescriptors:mySortDescriptors];

Related

Default list in Objective C?

I want to store data at run time, I can have a linked list and add at runtime, however as I am new to IOS and objective C, do we have any default list in which we can add our datas, (Datas are two stings and an integer).
Cocoa provides NSArray and NSMutableArray, a pair of ordered containers similar to Java's ArrayList and C#'s List. You can add values to NSMutableArray, and it will grow as you add more elements; NSArray is read-only.
You can use .plist files to store your data.
Read more 'Loading data from .plist files', 'How to use plist in iphone?' or google it like 'load data from .plist'. However you can create NSArray or something like this at run time. If you want dive deeper you must read ObjC Collections Programming Topics
Make a class for your data with default properties and make sure it inherits NSObject then use NSMUtableArray to add/remove elements to the list.
// in the .h file of your object
#interface MyObject : NSObject {
NSString* strAttribute1;
// add more attributes as you want
}
#property (nonatomic, retain) NSString* strAttribute1;
#end
// then in the .m file
// do not forget the #import ""
#implement MyObject
#synthesize strAttribute1;
// override the dealloc to release the retained objects
#end
then in your code where you want to make a list of this object
NSMutableArray* myArray = [[NSMutableArray alloc] init];
// add elements and iterate through them
// do not forgot to free the memory if you are not using ARC
[myArray release];
You can use NSArray or NSMutableArray or NSDictionary or NSMutableDictionary depending on your needs.
NSArray:
NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = #"a string";
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];
NSMutableArray:
NSMutableArray *myArray = [[NSMutableArray alloc] init];
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = #"a string";
[myArray addObject:aDate];
[myArray addObject:aValue];
[myArray addObject:aString];
NSDictionary:
NSDictionary * myDict = [NSDictionary dictionaryWithObjects:aDate, aValue, aString forKeys:firstDate, firstValue, firstString];
NSMutableDictionary:
NSString *aString = #"a string";
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
myDict = [[NSMutableDictionary alloc] init];
[myDict setObject:aString forKey:firstString];
[myDict setObject:aDate forKey:firstDate];
[myDict setObject:aValue forKey:firstValue];

Sort a complex NSarray

I have an NSArray *userInputs, this array contains custom objects "UserInput".
#interface UserInput :NSObject {
NSString *page_id;
#end
Each userInput ( instance of UserInput) belog to BookPage.
#interface BookPage: NSobject {
NSString *pagePrefix; ( exemple : pagePrefix = #"K1")
#end
From each userInput i know to witch BookPage it's belong like this :
BookPage *bookPage = [self.book pageWithID:userInput.page_id];
how i can sort an array of userInputs ( instances of UserInputs) with the pagePrefix Key. Thanks for your answers ?
You can sort the array of custom object like this:
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"pagePrefix" ascending:YES];
[userInputs sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];
You can sort array like(considering your array contains strings) -
sortedArray = [userInput sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
I think there is a book property in the middle?
NSSortDescriptor *aSortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"book.pagePrefix" ascending:YES];
[userInputs sortUsingDescriptors:[NSArray arrayWithObject:aSortDescriptor]];

sorting NSmutable array contains object according to double value

I want to order NSMutableArray contain objects according to two of object property one of them has double type second has NSString ?
I tried to use this method but I got exception :
NSString * LASTNAME = #"lastName";
NSString * GRADE = #"grade";
NSSortDescriptor *lastDescriptor =
[[NSSortDescriptor alloc]
initWithKey:LASTNAME
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)];
NSSortDescriptor *firstDescriptor =
[[NSSortDescriptor alloc]
initWithKey:GRADE
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)]];
NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, firstDescriptor, nil];
NSArray * sortedArray =
[students sortedArrayUsingDescriptors:descriptors];
#interface Student : NSObject
{
NSString * firstName;
NSString * lastName;
double grade;
}
NSNumber doesn't respond to localizedCaseInsensitiveCompare:. You want just plain compare: for the number.
Numbers don't have a case, try using compare: for GRADE
After Edit: You didn't say what error you got. Did the code you posted even compile? You have a typo in your firstDescriptor -- one too many "]" at the end of the method. You probably fixed that when you took out the compare: (which shouldn't have fixed anything).
Remove localizedCaseInsensitiveCompare
NSSortDescriptor *firstDescriptor =
[[NSSortDescriptor alloc]
initWithKey:GRADE
ascending:YES]];

Sorting and matching

NSMutableArray *full_text_list = [[NSMutableArray alloc]init];
[full_text_list addObject:#"for"];
[full_text_list addObject:#"for your information"];
[full_text_list addObject:#"you"];
[full_text_list addObject:#"at"];
NSMutableArray *short_text_list = [[NSMutableArray alloc]init];
[short_text_list addObject:#"4"];
[short_text_list addObject:#"fyi"];
[short_text_list addObject:#"u"];
[short_text_list addObject:#"#"];
i dont want to sort the second array. i want to get the appropriate element based on index.
I want to sort only the full_text_list array based on length, so i tried a below
NSSortDescriptor * descriptors = [[[NSSortDescriptor alloc] initWithKey:#"length"
ascending:NO] autorelease];
NSArray * sortedArray = [full_text_list sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptors]];
and the above code works fine.But i am not sure how to match short_text_list array with new sorted array
So when doing like [full_text_list objectatindex:0] and [short_text_list objectatindex:0] will not match
result would be "for your information" and "for" but the result should be "for your information" and "fyi"
Please let me know
How should it match? You have two arrays and are just sorting one and expect the second one automagically gets sorted too? This can not work. Why don't you just build a dictionary with the long information as key and the short one as value or vs?
A second way to do this would be:
// Create your two arrays and then combine them into one dictionary:
NSDictionary *textDict = [NSDictionary dictionaryWithObjects:short_text_list
forKeys:full_text_list];
// Create your sorted array like you did before:
NSSortDescriptor * descriptors = [[[NSSortDescriptor alloc] initWithKey:#"length" ascending:NO] autorelease];
NSArray * sortedArray = [full_text_list sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptors]];
// Then to access short_text, you would use:
NSString *object0ShortText = [textDict objectForKey:[sortedArray objectAtIndex:0]];
I would create a new class which contains both values and insert that into the array instead of creating the two separate array's in the first place:
#interface TextList : NSManagedObject
#property (nonatomic, retain) NSString *full_text;
#property (nonatomic, retain) NSString *short_text;
- (TextList *)initWithFullText:(NSString *)full_text shortText:(NSString *)short_text;
#end
Create your .m file, and then when you want to use it, use something like:
NSMutableArray *full_text_list = [[NSMutableArray alloc]init];
[full_text_list addObject:[TextList initWithFullText:#"for" shortText:#"4"]];
[full_text_list addObject:[TextList initWithFullText:#"for your information" shortText:#"fyi"]];
[full_text_list addObject:[TextList initWithFullText:#"you" shortText:#"u"]];
[full_text_list addObject:[TextList initWithFullText:#"at" shortText:#"#"]];
Then perform the sort:
NSSortDescriptor * descriptors = [[[NSSortDescriptor alloc] initWithKey:#"full_text.length" ascending:NO] autorelease];
NSArray * sortedArray = [full_text_list sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptors]];
Now you can do [[sortedArray objectAtIndex:0] full_text]; and [[sortedArray objectAtIndex:0] short_text]; or
TextList *txtList = [sortedArray objectAtIndex:0];
// txtList.full_text and txtList.short_text are both valid.

How do I alphabetically sort a custom object field within a NSMutable Array?

I have a custom object like:
#import <Foundation/Foundation.h>
#interface Store : NSObject{
NSString *name;
NSString *address;
}
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *address;
#end
I have an array of NSMutableArray (storeArray) containing Store objects:
store1 = [[Store alloc] init];
store1.name = #"Walmart";
store1.address = #"walmart address here..";
store2 = [[Store alloc] init];
store2.name = #"Target";
store2.address = #"Target address here..";
store3 = [[Store alloc] init];
store3.name = #"Apple Store";
store3.address = #"Apple store address here..";
//add stores to array
storeArray = [[NSMutableArray alloc] init];
[storeArray addObject:store1];
[storeArray addObject:store2];
[storeArray addObject:store3];
My question is how can I sort the array by the store name? I know I can sort an array alphabetically by using this line:
[nameOfArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
How can I apply this to the store name of my Store class?
NSSortDescriptor *sortDescriptor =
[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(caseInsensitiveCompare:)];
[nameOfArray sortedArrayUsingDescriptors:#[sortDescriptor]];
Related documentation:
[NSArray sortedArrayUsingDescriptors:]
NSSortDescriptor
Regexident's answer is based on NSArrays, the corresponding in-place sorting for NSMutableArray would be -sortUsingDescriptors:
[storeArray sortUsingDescriptors:
[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(caseInsensitiveCompare:)]]];
Now storeArray it-self will be sorted.