I'm trying to add an dictionary to an array to create an array on dictionaries, but when I test the app, the array is still empty. Take a look on my code:
NSMutableArray *listaEstabelecimentosPorCategoria;
for (NSDictionary *tempDict in listaEstabelecimentos) {
if ([[tempDict objectForKey:#"category"] integerValue] == 1) {
[listaEstabelecimentosPorCategoria addObject:tempDict];
NSLog(#"TEST");
}
}
NSLog(#"%#", listaEstabelecimentosPorCategoria);
The app prints this:
2013-08-18 12:16:38.802 Petrópolis[10157:c07] TEST
2013-08-18 12:16:38.802 Petrópolis[10157:c07] TEST
2013-08-18 12:16:38.803 Petrópolis[10157:c07] (null)
when I test the app, the array is still empty.
This is because you did not initialize listaEstabelecimentosPorCategoria:
NSMutableArray *listaEstabelecimentosPorCategoria = [NSMutableArray array];
NSMutableArray *listaEstabelecimentosPorCategoria=[[NSMutableArray alloc] init]; //initialize
for (NSDictionary *tempDict in listaEstabelecimentos) {
if ([[tempDict objectForKey:#"category"] integerValue] == 1) {
[listaEstabelecimentosPorCategoria addObject:tempDict];
NSLog(#"TEST");
}
}
NSLog(#"%#", listaEstabelecimentosPorCategoria);
NSMutableArray *listaEstabelecimentosPorCategoria this code hasn't been allocated to memory so it will be null value
NSMutableArray *listaEstabelecimentosPorCategoria = [NSMutableArray array];
then listaEstabelecimentosPorCategoria add the object.
Related
Hello I have a NSMutableDictionary like this
<__NSArrayM 0x14e226ff0>(
{
DocumentName = "IMG_2597.JPG";
DocumentType = JPG;
Image = "<UIImage: 0x14e52c370> size {1239, 1242} orientation 0 scale 1.000000";
}
I am adding several objects into my NSMutablearray. But I want to check whether this image already available in the NSMutablearray. Actually I am planing to search it by the DocumentName. How can I check whether that same value is already exists for the DocumentName key in the array. I want to add the NSMutableDictionary if only its not already exists. This is how I create my NSMutabledictionaryobject.
NSMutableDictionary *imageDictionary=[[NSMutableDictionary alloc] init];
[imageDictionary setObject:chosenImage forKey:#"Image"];
[imageDictionary setValue:strDocNAme forKey:#"DocumentName"];
[imageDictionary setValue:strExtension forKey:#"DocumentType"];
[mutarrayImages addObject:imageDictionary];
Please help me.
Thanks
You can try one of these to check image is already exist or not.
1) Using predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"DocumentName = 'IMG_2597.JPG'"];
NSArray *arr = [yourArray filteredArrayUsingPredicate:predicate];
if (arr.count > 0) {
NSLog(#"Object is contain");
}
2) Using valueForKey
NSArray *documentName = [yourArray valueForKey:#"DocumentName"];
if ([documentName containsObject:#"IMG_2597.JPG"]) {
NSLog(#"Object is contain");
}
NSSet* myValuesSet = [NSSet setWithArray: [mutarrayImages valueForKey:#"DocumentName"]];
if ([[myValuesSet allObjects] containsObject:< DocumentName to compare >]) {
NSLog(#"Exist");
}
else{
NSLog(#"Does not exist");
}
NSArray *allObjectsArray; // your array
NSMutableArray *resultObjectsArray = [NSMutableArray array];
for(NSDictionary *dict in allObjectsArray)
{
NSString *docName = [dict objectForKey:#"DocumentName"];
NSRange range = [docName rangeOfString:#"your string which you want to match" options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
[resultObjectsArray addObject:dict];
}
Im trying to filter through an array and get rid of all the duplicate strings.
NSMutableArray *initialWomensCategoryArray = [NSMutableArray new];
for(NSArray *womensCategoryInnner in [objects valueForKey:#"womensCategory"])
{
for(id object in womensCategoryInnner)
{
[initialWomensCategoryArray addObject:object];
womensDataArray = [[NSMutableArray alloc]init];
for (id obj in initialWomensCategoryArray)
{
if (![womensDataArray containsObject:obj])
{
[womensDataArray addObject: obj];
}
}
}
}
Above Error want to say "You have getting NULL value" when you have add Object into array. So you have two possibility for this error
1) [initialWomensCategoryArray addObject:object]
2) [womensDataArray addObject: obj]
I think you have to check for the first one([initialWomensCategoryArray addObject:object])
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.
i have two nsmutableArray . Arr_jsondata and second is tempArray.
Already Arr_jsondata contain the data from json link and display in tableview .
i want to add the tempArray data into Arr_jsondata and reload the table using Arr_jsondata , because tableview delegate is also used this array to display the data in tableview .
but its always give me an error when i add temp array data into arr_jsondata .
for (int i=0; i<[Temp_arr_JsonData count]; i++)
{
NSString *str_brandname = [[Temp_arr_JsonData objectAtIndex:i] valueForKey:#"storebrand"];
NSLog(#"%#",str_brandname);
NSObject *myNewObject = [[NSObject alloc] init];
if ([str_brandname isEqualToString:#"Nike"])
{
NSLog(#"Data matched");
c++;
myNewObject = [Temp_arr_JsonData objectAtIndex:i];
[temparray addObject:myNewObject];
}
}
// arr_JsonData=temparray;
[[arr_JsonData arrayByAddingObjectsFromArray:temparray] mutableCopy];
NSLog(#"%#",temparray);//display all nike related data
NSLog(#"%#",arr_JsonData);//display null array .
[self.tableView reloadData];
[sender setSelected:YES];
in last i want only tempdata into Arr_jsondata ..... what can i do ?
Just add objects from array. See this apple's doc
if (arr_JsonData.count > 0)
[arr_JsonData addObjectsFromArray: (NSArray*)temparray];
else
arr_JsonData = [NSMutableArray arrayWithArray:(NSArray*)temparray]
You can try this
[arr_JsonData addObjectsFromArray:tempArray];
I think arr_JsonData is not NSMutableArray actually which can be judged from the exception description you listed in the answer. Try this:
arr_JsonData = [NSMutableArray arrayWithArray:arr_JsonData];
[arr_JsonData addObjectsFromArray: temparray];
Try using this:
NSMutableArray *ar = [NSMutableArray alloc] initWithArray:ar1];
Just have to initialize array with other array and it will have all contents from other array.
Or this one:
NSMutableArray *ar = [NSMutableArray alloc] initWithArray:ar1 copyItems:YES];
mutableCopy is defined for NSArray not for NSMutableArray
if ([arr_JsonData count] > 0)
{
[arr_JsonData addObjectsFromArray: temparray];
}
We have an app that calls a SOAP web service and retrieves a long list of XML, which the app then parses into an NSArray of NSDictionary objects. The NSArray contains a list of Rental Apartment information, each of which is stored into an NSDictionary.
The entire list may contain 10 different types of Apartments (i.e. 2-room, 3-room), and we need to split the NSArray into smaller NSArrays based on Room-Type, which has the key "roomType" in the NSDictionary objects.
Currently our algorithm is
Use [NSArray valueForKeyPath:#"#distinctUnionofObjects.room-type"]
to obtain a list of unique room-type values.
Loop through the list of unique room-type values
For each unique room-type value, use NSPredicate to retrieve matching items from the Original list
Our code is below (renamed for clarity):
NSArray *arrOriginal = ... ...; // Contains the Parsed XML list
NSMutableArray *marrApartmentsByRoomType = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *arrRoomTypes = [arrOriginal valueForKeyPath:#"distinctUnionOfObjects.roomType"];
for(NSString *strRoomType in arrRoomTypes) {
NSPredicate *predicateRoomType = [NSPredicate predicateWithFormat:#"roomType=%#", strRoomType];
NSArray *arrApartmentsThatMatchRoomType = [arrOriginal filteredArrayUsingPredicate:predicateRoomType]; // TAKES A LONG TIME EACH LOOP-ROUND
[marrApartmentsByRoomType addObject:arrApartmentsThatMatchRoomType];
}
However, step 3 is taking a long time as the original list may contain large amount (>100,000) of items. It seems that NSPredicate goes through the entire list for each key value. Is there a more efficient way of splitting a large NSArray into smaller NSArrays, based on NSDictionary keys?
If the order of your splited Arrays is not important, i have a solution for you:
NSArray *arrOriginal;
NSMutableDictionary *grouped = [[NSMutableDictionary alloc] initWithCapacity:arrOriginal.count];
for (NSDictionary *dict in arrOriginal) {
id key = [dict valueForKey:#"roomType"];
NSMutableArray *tmp = [grouped objectForKey:key];
if (tmp == nil) {
tmp = [[NSMutableArray alloc] init];
[grouped setObject:tmp forKey:key];
}
[tmp addObject:dict];
}
NSMutableArray *marrApartmentsByRoomType = [grouped allValues];
This is quite performant
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
Improving #Jonathan answer
Converting array to dictionary
Maintaining the same order as it was in original array
//only to a take unique keys. (key order should be maintained)
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
NSMutableDictionary *dictFromArray = [NSMutableDictionary dictionary];
for (NSDictionary *eachDict in arrOriginal) {
//Collecting all unique key in order of initial array
NSString *eachKey = [eachDict objectForKey:#"roomType"];
if (![aMutableArray containsObject:eachKey]) {
[aMutableArray addObject:eachKey];
}
NSMutableArray *tmp = [grouped objectForKey:key];
tmp = [dictFromArray objectForKey:eachKey];
if (!tmp) {
tmp = [NSMutableArray array];
[dictFromArray setObject:tmp forKey:eachKey];
}
[tmp addObject:eachDict];
}
//NSLog(#"dictFromArray %#",dictFromArray);
//NSLog(#"Unique Keys :: %#",aMutableArray);
//Converting from dictionary to array again...
self.finalArray = [[NSMutableArray alloc]init];
for (NSString *uniqueKey in aMutableArray) {
NSDictionary *aUniqueKeyDict = #{#"groupKey":uniqueKey,#"featureValues":[dictFromArray objectForKey:uniqueKey]};
[self.finalArray addObject:aUniqueKeyDict];
}
Hope, It will help when client wants final array in same order as input array.