objective-c spilt array in multiple arrays for uitableview grouped - objective-c

hi i have an array of objects which need to be sorted (alphabet on name)
ArtistVO *artist1 = [ArtistVO alloc];
artist1.name = #"Trentemoeller";
artist1.imgPath = #"imgPath";
ArtistVO *artist2 = [ArtistVO alloc];
artist2.name = #"ATrentemoeller";
artist2.imgPath = #"imgPath2";
ArtistVO *artist3 = [ArtistVO alloc];
artist3.name = #"APhextwin";
artist3.imgPath = #"imgPath2";
//NSLog(#"%#", artist1.name);
NSMutableArray *arr = [NSMutableArray array];
[arr addObject:artist1];
[arr addObject:artist2];
[arr addObject:artist3];
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"name"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray =
[arr sortedArrayUsingDescriptors:descriptors];
NSLog(#"\nSorted ...");
NSEnumerator *enumerator;
enumerator = [sortedArray objectEnumerator];
ArtistVO *tmpARt;
while ((tmpARt = [enumerator nextObject])) NSLog(#"%#", tmpARt.name);
works fine. but now i need to split this awway up for usage in a grouped uitableview
self.sortedKeys =[[NSArray alloc]
initWithObjects:#"{search}",#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z",nil];
NSMutableArray *arrTemp0 = [[NSMutableArray alloc]
initWithObjects:#"000",nil];
NSMutableArray *arrTemp1 = [[NSMutableArray alloc]
initWithObjects:#"Andrew",#"Aubrey",#"Aalice", #"Andrew",#"Aubrey",#"Alice",#"Andrew",#"Aubrey",#"Alice",nil];
NSMutableArray *arrTemp2 = [[NSMutableArray alloc]
initWithObjects:#"Bob",#"Bill",#"Bianca",#"Bob",#"Bill",#"Bianca",nil];
NSMutableArray *arrTemp3 = [[NSMutableArray alloc]
initWithObjects:#"Candice",#"Clint",#"Chris",#"Candice",#"Clint",#"Chris",nil];
NSMutableArray *arrTemp4 = [[NSMutableArray alloc]
initWithObjects:#"Dandice",#"Dlint",#"Dhris",nil];
NSDictionary *temp =[[NSDictionary alloc]
initWithObjectsAndKeys:arrTemp0, #"{search}", arrTemp1,#"A",arrTemp2,
#"B",arrTemp3,#"C",arrTemp4,#"D",nil];
self.tableContents =temp;
so all Artist with first letter "a" come in one array ... with "b" in one array and so on.
do i need to do some string comparism or is there a better approach?

How about:
Create an empty NSMutableDictionary.
Loop through all your strings. For each string:
If string is empty, ignore this string.
Get a NSString containing first character of the string converted to uppercase. This will be your dictionary key.
Look in the dictionary to see if it already contains this key.
If not, create a new NSMutableArray containing just your string and add it as the value to this new key.
If so, add this string to the end of the existing array.
End of loop.

Related

Accessing descriptors in array of arrays

I have a mutable array containing some arrays for use in a table view controller. The arrays contain a title and some other information. I want the arrays in the master array to be sorted alphabetically in terms of the title they contain. I have assigned the titles with keys:
NSString *title = #"objectTitle";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_storedTitle.text, title, nil];
NSArray *newArray = #[#"Login", dict, _storedUsername.text, _storedPassword.text];
I store the newArray in my masterArray and try to sort the array thus:
//sort array alphabetically
NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:#"objectTitle" ascending:YES];
NSArray *sortDescriptors = #[titleDescriptor];
NSArray *sortedArray = [_masterArray sortedArrayUsingDescriptors:sortDescriptors];
_masterArray = sortedArray.copy;
This is not working, as i have not specified the index where the titleDescriptor is stored. How do I do this?
When accessing the title at a given index (index) in the master array is done as follows:
NSLog(#"%#", [[[_masterArray objectAtIndex:index] objectAtIndex:1] objectForKey:#"objectTitle"]);
Modified your code like this:-
NSSortDescriptor *sortedDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"objecttitle"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:sortedDescriptor, nil];
NSArray * sortedArray =
[array sortedArrayUsingDescriptors:descriptors];
NSlog(#"%#",sortedArray);

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

Fast way to search the properties of objects in an NSArray

I have an NSArray of custom objects that all have a #property name of type NSString. How can I quickly enumerate through the array and create a new array that contains only the objects that have a specific word in their name property?
For instance:
CustomObject *firstObject = [[CustomObject alloc] init];
firstObject.name = #"dog";
CustomObject *secondObject = [[CustomObject alloc] init];
secondObject.name = #"cat";
CustomObject *thirdObject = [[CustomObject alloc] init];
thirdObject.name = #"dogs are fun";
NSMutableArray *testArray = [NSMutableArray arrayWithObjects:firstObject,
secondObject,
thirdObject,
nil];
// I want to create a new array that contains all objects that have the word
// "dog" in their name property.
I know I could use a for loop like so:
NSMutableArray *newArray = [NSMutableArray array];
for (CustomObject *obj in testArray)
{
if ([obj.name rangeOfString:#"dog"].location == NSNotFound) {
//string wasn't found
}
else {
[newArray addObject:obj];
}
}
But is there a more efficient way? Thanks!
NSString *searchString = #"dog";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.name contains %#", searchString];
NSArray *filteredArray = [testArray filteredArrayUsingPredicate:predicate];
Please have a look at NSPredicates ! They are highly efficient when you are searching / filtering through array results. This is the documentation!

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 can I retrieve all the contents of an NSDictionary?

I want to select and retrieve all the contents from an NSDictionary. I have a structure like this
- (void)viewDidLoad {
[super viewDidLoad];
listaOggetti = [[NSMutableArray alloc] init];
NSArray *arrayOne = [NSArray arrayWithObjects: #"First",#"Second",#"Third", nil];
NSArray *sortedOne = [arrayOne sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictOne = [NSDictionary dictionaryWithObject:sortedOne forKey:#"Elementi"];
NSArray *arrayTWo = [NSArray arrayWithObjects:#"First1",#"Second1" ..., nil];
NSArray *sortedTwo = [arrayTwo sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictTwo = [NSDictionary dictionaryWithObject:sortedTWo forKey:#"Elementi"];
NSArray *arrayThree = [NSArray arrayWithObjects:#"First2",#"Second2" ... , nil];
NSArray *sortedThree = [arrayThree sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSDictionary *dictThree = [NSDictionary dictionaryWithObject:sortedThree forKey:#"Elementi"];
[listaOggetti addObject:dictOne];
[listaOggetti addObject:dictTwo];
[listaOggetti addObject:dictThree];
}
And I want to retrieve all the objects for the key #"Elementi" (should be around 45) in order to add them in another array, like:
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
NSArray *array = [dict objectForKey:#"Elementi"];
cellValue = [array objectAtIndex:indexPath.row] ;
(With this, dict is only 9 objects filled in my project).
At the end, the *array should be around 45 objects filled. I tried with allValues, but didn't work.
How can I fix it?
The easiest is to do this in -viewDidLoad:
NSMutableArray *allObjects = [[NSMutableArray alloc] init];
[allObjects addObjectsFromArray:sortedOne];
[allObjects addObjectsFromArray:sortedTwo];
[allObjects addObjectsFromArray:sortedThree];
Alternately, you can get them from the dictionaries in a similar fashion:
NSMutableArray *allObjects = [[NSMutableArray alloc] init];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:0] objectForKey#"Elementi"];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:1] objectForKey#"Elementi"];
[allObjects addObjectsFromArray:[[listaOggetti objectAtIndex:2] objectForKey#"Elementi"];
What you are failing to understand is that listaOggetti is an NSMutableArray containing three objects. When you call
NSDictionary *dict = [listaOggetti objectAtIndex:indexPath.section];
the result is that dict is a single dictionary, one of the three objects in listaOggetti. Therefore when you call
NSArray *array = [dict objectForKey:#"Elementi"];
the result is that array is the object for the key #"Elementi" of that one single dictionary dict. Your code makes no attempt to combine the three DIFFERENT dictionaries or to combine the three arrays, each set as objectForKey:#"Elementi" for the three DIFFERENT dictionaries.
If you want one array that is the concatenation of all three different arrays, then use one of the snippets provided above. In both of these snippets, the result is that allObjects is an NSMutableArray containing all three arrays, in order.