Sort Objectsdictionnary - ios

I have a tableview that contains multiple sections, grouped by an attribute of my object (date) I try to sort the tableview according to the value of date.I created a function for that , but I get an error :
- (void)sortObjectsDictionnary:(NSArray *)arrayObjects
{
//this is my nsdictionnary
[objects removeAllObjects]
//this is nsmutableaaray that contains dats
[objectsIndex removeAllObjects];
NSMutableSet *keys = [[NSMutableSet alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy/MM/dd"];
for(int i=0;i<[arrayObjects count];i++){
Task *myTask=[arrayObjects objectAtIndex:i];
//curentsection contains my objects whith dates
NSMutableArray *currentSection = [objects objectForKey:taskDate];
if (currentSection == nil)
{
[keys addObject:taskDate];
currentSection = [[[NSMutableArray alloc] init] autorelease];
[objects setObject:currentSection forKey:taskDate];
}
// we add objet to the right section
[currentSection addObject:myTask];
}
[dateFormatter release];
for (id element in keys)
{
[objectsIndex addObject:element];
NSMutableArray *currentSection = [objects objectForKey:element];
//I get an error in this line
[currentSection sortUsingSelector:#selector(compare:)];
}

You haven't mentioned what the error message is and I am assuming the error message may be due to accessing NSMutableArray array object without initializing it. Try an alloc and init for array before
NSMutableArray *currentSection = [NSMutableArray]alloc]init];
currentSection = [objects objectForKey:element];
//I get an error in this line
[currentSection sortUsingSelector:#selector(compare:)];
Well it is purely a guess. Post your error message if this not works.
Bharath

Related

Add Array values to NSMutableDictionary

I ran into a problem and I can't find the method to get over it. basically I need to make a mutable dictionary with some values. All values are dynamic and I get them from web service or from other variables.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:comment.text forKey:#"Comment"];
[dict setObject:name.text forKey:#"Name"];
[dict setObject:[NSString stringWithFormat:#"%d",isPublic] forKey:#"VisibleForAll"];
po dict
{
Comment = "no comment";
Name = "test";
VisibleForAll = 1;
-> carts
}
Furthermore I want to add the following tree to my dictionary but I can't figure how to do this.
I have the necessary items in 2 NSArray artID and qty but I don't know how to create the bottom part so I can add it to the dict.
Carts {
Cart {
ArticleID : 22
Quantity : 1
}
Cart {
ArticleID : 45
Quantity : 3
}
...
}
I will add it with [dict setObject:carts forKey:#"Cart"] but I don't know how to add values in such a manner that I will make my dictionary on the form I presented you.
Also, don't forget that the numbers or Carts is flexible. I will get it from a Product.count.
Thanks in advance.
If your both array artID and qty have value at the same index for create a dictionary you can try like this
NSMutableArray *carts = [[NSMutableArray alloc] init];
for(NSInteger i=0; i<products.count; i++) {
//If you have custom class `cart` than use that
Cart *cart = [[Cart alloc] init];
cart.ArticleID = [[products objectAtIndex:i] valueForKey:#"pid"];
cart.Quantity = [[products objectAtIndex:i] valueForKey:#"qty"];
//If you not have any custom class than use Dictionary
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"ArticleID"];
[cart setObject:[[products objectAtIndex:i] valueForKey:#"pid"] forKey:#"Quantity"];
}
Now add this carts array to Dictionary with key
[dict setObject:carts forKey:#"carts"];
NSArray *pid = [products valueForKey:#"pid" ];
NSArray *qty = [products valueForKey:#"qty"];
NSMutableArray *carts = [[NSMutableArray alloc] initWithCapacity:products.count];
for(NSInteger i=0; i<products.count; i++) {
NSMutableDictionary *cart = [[NSMutableDictionary alloc] init];
NSMutableDictionary *cartemp = [[NSMutableDictionary alloc] init];
[cart setObject:[pid objectAtIndex:i] forKey:#"ArticleId"];
[cart setObject:[qty objectAtIndex:i] forKey:#"Quantity"];
[cartemp setObject:cart forKey:#"Cart"];
[carts addObject:cartemp];
}
[dict setObject:carts forKey: #"Carts"];

Remove Duplicate custom objects from NSMutable Array making sure to keep newest duplicate object

I have an NSMutableArray of custom objects. Each contains an ID string that is unique, and each contains an downloadedDate property.
Objects could get added twice so I need to check the ID for duplicates, and if I find a duplicate I need to keep the one that has the newest date.
Currently I am doing the following to remove duplicates, but it doesn't take into account keeping the object with the newest date.
NSArray *originalArray = [NSArray arrayWithArray:mutableItems];
NSMutableArray *uniqueArray = [NSMutableArray array];
NSMutableSet *names = [NSMutableSet set];
for (ZSSObject *g in originalArray) {
NSString *destinationName = g.code;
if (![names containsObject:destinationName]) {
[uniqueArray addObject:g];
[names addObject:destinationName];
}
}
NSArray *uniqueObjects = uniqueArray;
Objects get created like this:
ZSSObject *obj = [ZSSObject alloc] init];
obj.code = #"12345";
obj.downloadedDate = [NSDate date];
Is there an easier way to do that I want than having a bunch of copies of my array and nested loops?
Using the suggestion to use an NSDictionary instead, I came up with this solution:
NSMutableDictionary *objDict = [[NSMutableDictionary alloc] init];
for (ZSSObject *g in mutableItems) {
ZSSObject *addedObj = objDict[g.code];
if (addedObj) {
// Compare dates
if ([addedObj respondsToSelector:#selector(dateDownloaded)]) {
if ([g.dateDownloaded compare:addedObj.dateDownloaded] == NSOrderedDescending) {
[objDict setObject:g forKey:g.code];
}
}
} else {
[objDict setObject:g forKey:g.code];
}
}
NSArray *uniqueObj = objDict.allValues;

Crash with a loop which look in a mutable array [duplicate]

I have the following situation where
I have an NSMutableArray filled with an xml file which I want to search.
When I enter something in the search field I get this Error:
-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x5b388b0
What does it means and how can I fix it??
I suppose the error is somewhere around here.
- (void)searchTableView{
searchedList = [[NSMutableArray alloc] init];
NSLog(#"new list %#", searchedList);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in list) {
NSArray *array = [dictionary objectForKey:#"TITLE"];
[searchArray addObjectsFromArray:array];
}
for (NSString *TempArray in searchArray) {
NSRange titleResults = [TempArray rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResults.length > 0)
[searchedList addObject:TempArray];
}
[searchArray release];
searchArray = nil;
}
it means you are calling a method designed for an NSArray (countByEnumeratingWithState:objects:count on a NSString.
I don't know ifthis code is copy/paste from yours, but if so, at the end where you use [searchList addObject:TempArray] you don't have an object named searchList.
Also, work on your naming conventions. big time.

mutable array value getting empty

I am having an array which contains a date. this is my array.
"2015-03-01",
"2015-03-04",
"2015-03-05",
"2015-03-06",
"2015-03-07",
"2015-03-08",
"2015-03-14",
"2015-03-15"
list the value according to this date.my coding is
NSArray * datevalue = [tempArr valueForKey:#"match_formatted_date"];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"self" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject: descriptor];
NSArray *reverseOrder = [datevalue sortedArrayUsingDescriptors:descriptors];
NSPredicate *findFutureDates = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind){
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *dd = [df dateFromString:(NSString *)obj ];
return ([[NSDate date] compare:dd] == NSOrderedAscending);
}];
NSArray * arrFutureDates = [reverseOrder filteredArrayUsingPredicate: findFutureDates];
NSLog(#"arrFutureDates:%#",arrFutureDates);
for (id item in arrFutureDates)
{
if (![dataArr containsObject:item])
[dataArr addObject:item];
}
[dataArr sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (int i= 0; i<[dataArr count]-1; i++) {
for (id item in tempArr)
{
if([#"Mexico: Copa Mexico - Clausura" isEqualToString:[item valueForKey:#"league_name"]]
||[#"Mexico: Liga De Ascenso - Clausura" isEqualToString:[item valueForKey:#"league_name"]]
||[#"Mexico: Primera Division - Clausura" isEqualToString:[item valueForKey:#"league_name"]])
if([[dataArr objectAtIndex:i]isEqualToString:[item valueForKey:#"match_formatted_date"]])
{
NSMutableDictionary *tempDic =[[NSMutableDictionary alloc]init];
[tempDic setValue: [item valueForKey:#"match_formatted_date"] forKey:#"match_formatted_date"];
[tempDic setValue: [item valueForKey:#"league_name"] forKey:#"league_name"];
if (![titleheader containsObject:tempDic])
{
[titleheader addObject:tempDic];
}}}}
my problem is: In title header null value is coming. were I made the mistake, can anyone help me.
Check your code, you didnt initialize titleheader anywhere. In that case it will be nil only.
Before checking condition, initialize and assign some value to titleheader.
Or else i dont know you missed to paste the code.
Unreadable formatting aside, there are few issues in your code, that may cause your problem:
NSArray* datevalue = [tempArr valueForKey:#"match_formatted_date"];
Name suggests, that tempArr is NSArray, however you are accessing it as NSDictionary. There is difference between methods -valueForKey: and -objectForKey:. Former is NSObject method related to KVC, while latter is NSDictionary method for accessing stored objects. They are frequently confused, because called on NSDictionary they behave in the same way.
for (int i= 0; i<[dataArr count]-1; i++) {
This for loop skips last object in dataArr, which - I assume - was not intended. This can be fixed by i < dataArr.count or i <= dataArr.count-1.
Another issue - not related to problem, but opportunity to learn:
NSMutableDictionary *tempDic =[[NSMutableDictionary alloc]init];
[tempDic setValue: [item valueForKey:#"match_formatted_date"] forKey:#"match_formatted_date"];
[tempDic setValue: [item valueForKey:#"league_name"] forKey:#"league_name"];
if (![titleheader containsObject:tempDic])
Objects in containers are stored and compared (by default) as references, thus -containsObject will always return NO - even if there were another NSDictionary with the same key-value pairs.

Why would my NSMutableDictionary be nil?

I am trying to store an array in a NSMutableDictionary. However the NSMutableDictionary is null after i have set objects to it. Here is my code any help is appreciated:
NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
NSMutableDictionary *dTemp = [[NSMutableDictionary alloc] init];
STStockData *stockData = [[STStockData alloc] init];
for (int i = 0; i < [_arrTickers count]; i++) {
// get the ticker from its json form
dTemp = [_arrTickers objectAtIndex:i];
NSLog(#"Ticker: %#",[dTemp objectForKey:#"ticker"]);
// gets current data for ticker
[arrTemp addObjectsFromArray:[stockData getCurrentStockDataForTicker:[dTemp objectForKey:#"ticker"]]];
NSLog(#"Price %#",[arrTemp objectAtIndex:1]); // just to prove the array isnt nil.
// adds it to the dictionary
[_dStockData setObject:arrTemp forKey:[dTemp objectForKey:#"ticker"]];
NSLog(#"Dictionary %#",_dStockData);
// remove all objects so can reuse.
[arrTemp removeAllObjects];
dTemp = nil; // can't remove objects using [removeAllObjects] method. believe its due to it holding inside NSArrays which are immutable.
}
Here is the console output:
Initialize _dStockData
_dStockData = [[NSMutableDictionary alloc] init];
It is nil because use initialize stockData
STStockData *stockData = [[STStockData alloc] init];
and print _dStockData
NSLog(#"Dictionary %#",_dStockData);

Resources