iOS: value not coming as String? - ios

In my code, I set array inside a NSMutableDictionary as
if (array.count > 0) {
[self.filters setValue:array forKey:[self getKey:[[NSNumber numberWithInt:indexPath.section] intValue]]];
}
where array is
NSMutableArray *array = [[NSMutableArray alloc] init];
When the receiving code receives it, I tried to join the values in array as
if ([item objectForKey:#"category_filter"] != nil) {
NSArray *array = [NSArray arrayWithObjects:[item objectForKey:#"category_filter"], nil];
NSString *categories = [array componentsJoinedByString:#","];
NSLog(#"value:%#", categories);
}
where item is (NSMutableDictionary *)item
When I see log, I see as
2014-06-24 17:43:12.520 yelp[69744:70b] value:(
"Bagels (bagels)",
"Bakeries (bakeries)"
)
so they are not joined yet. What am I doing wrong here?

As Hot Licks commented,
I had to make change as
NSArray *array = [NSArray arrayWithArray:[item objectForKey:#"category_filter"]];
instead of
NSArray *array = [NSArray arrayWithObjects:[item objectForKey:#"category_filter"]];

Related

Sort array in ascending order and remove duplicate values in objective- c

I have a horizontally and vertically scrollable table. I get the data for the header and first column from the web service(json). I want to sort the data in ascending order and remove duplicate data from both header and the first column. For removing duplicate values I used the following code:
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];
headData = [[NSMutableArray alloc] init];
NSMutableArray *head = [[NSMutableArray alloc] init];
leftTableData = [[NSMutableArray alloc] init];
NSMutableArray *left = [[NSMutableArray alloc] init];
rightTableData = [[NSMutableArray alloc]init];
for (NSMutableArray *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [[dictionary valueForKey:#"cid"]intValue];
model.iid = [[dictionary valueForKey:#"iid"]intValue];
model.yr = [[dictionary valueForKey:#"yr"]intValue];
model.val = [dictionary valueForKey:#"val"];
[mainTableData addObject:model];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
}
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
headData = [[orderedSet array] mutableCopy];
// NSSet *set = [NSSet setWithArray:left];
// NSArray *array2 = [set allObjects];
// NSLog(#"%#", array2);
NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];
//remove duplicate enteries from header array
[leftTableData addObject:arrLeft];
NSMutableArray *right = [[NSMutableArray alloc]init];
for (int i = 0; i < arrLeft.count; i++)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int j = 0; j < headData.count; j++)
{
/* NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
How will I sort the arrays in ascending order?
Please help.
OK, so you have a model object that looks something like this...
#interface Model: NSObject
#property NSNumber *idNumber;
#property NSNumber *year;
#property NSString *value;
#end
Note, I am intentionally using NSNumber and not NSInteger for reasons that will become clear.
At the moment you are trying to do a lot all in one place. Don't do this.
Create a new object to store this data. You can then add methods to get the data you need. Seeing as you are displaying in a table view sectioned by year and then each section ordered by idNumber then I'd do something like this...
#interface ObjectStore: NSObject
- (void)addModelObject:(Model *)model;
// standard table information
- (NSInteger)numberOfYears;
- (NSInteger)numberOfIdsForSection:(NSinteger)section;
// convenience methods
- (NSNumber *)yearForSection:(NSInteger)section;
- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row;
- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row;
// now you need a way to add objects
- (void)addModelObject:(Model *)model;
#end
Now to implement it.
We are going to store everything in one dictionary. The keys will be years and the objects will be dictionaries. In these dictionaries the keys will be idNumbers and the objects will be arrays. These array will hold the models.
So like this...
{
2010 : {
1 : [a, b, c],
3 : [c, d, e]
},
2013 : {
1 : [g, h, u],
2 : [e, j, s]
}
}
We'll do this with all the convenience methods also.
#interface ObjectStore: NSObject
#property NSMutableDictionary *objectDictionary;
#end
#implementation ObjectStore
+ (instancetype)init
{
self = [super init];
if (self) {
self.objectDictionary = [NSMutableDictionary dictionary];
}
return self;
}
+ (NSInteger)numberOfYears
{
return self.objectDictionary.count;
}
+ (NSInteger)numberOfIdsForSection:(NSinteger)section
{
// we need to get the year for this section in order of the years.
// lets create a method to do that for us.
NSNumber *year = [self yearForSection:section];
NSDictionary *idsForYear = self.objectDictionary[year];
return idsForYear.count;
}
- (NSNumber *)yearForSection:(NSInteger)section
{
// get all the years and sort them in order
NSArray *years = [[self.obejctDictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
// return the correct year
return years[section];
}
- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row
{
// same as the year function but for id
NSNumber *year = [self yearForSection:section];
NSArray *idNumbers = [[self.objectDictionary allKeys]sortedArrayUsingSelector:#selector(compare:)];
return idNumbers[row];
}
- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row
{
NSNumber *year = [self yearForSection:section];
NSNumber *idNumber = [self idForSection:section row:row];
return self.objectDictionary[year][idNumber];
}
// now we need a way to add objects that will put them into the correct place.
- (void)addModelObject:(Model *)model
{
NSNumber *modelYear = model.year;
NSNumber *modelId = model.idNumber;
// get the correct storage location out of the object dictionary
NSMutableDictionary *idDictionary = [self.objectDictionary[modelYear] mutableCopy];
// there is a better way to do this but can't think atm
if (!idDictionary) {
idDictionary = [NSMutableDictionary dictionary];
}
NSMutableArray *modelArray = [idDictionary[modelId] mutableCopy];
if (!modelArray) {
modelArray = [NSMutableArray array];
}
// insert the model in the correct place.
[modelArray addObject:model];
idDictionary[modelId] = modelArray;
self.objectDictionary[modelYear] = idDictionary;
}
#end
With all this set up you can now replace your complex function with this...
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonDictionary = [parser objectWithString:theJSON error:nil];
for (NSDictionary *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [dictionary valueForKey:#"cid"];
model.idNumber = [dictionary valueForKey:#"iid"];
model.year = [dictionary valueForKey:#"yr"];
model.val = [dictionary valueForKey:#"val"];
[self.objectStore addModelObject:model];
}
}
To get the models out for a particular row then just use...
[self.objectStore modelsForSection:indexPath.section row:indexPath.row];
To get the number of sections in the tableview delegate method...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.objectStore numberOfYears];
}
No messing around with the model in the view controller.
Welcome to the MVC pattern.
There's a crap ton of code here but by placing all the code here you can remove all the complex code from your VC.
NSSet keeps only non-duplicate objects within themselves so to keep only unique objects in array you can use NSSet as -
Suppose you have array with duplicate objects
NSArray *arrayA = #[#"a", #"b", #"a", #"c", #"a"];
NSLog(#"arrayA is: %#", arrayA);
//create a set with the objects from above array as
//the set will not contain the duplicate objects from above array
NSSet *set = [NSSet setWithArray: arrayA];
// create another array from the objects of the set
NSArray *arrayB = [set allObjects];
NSLog(#"arrayB is: %#", set);
The output from the above looks like:
arrayA is: (
a,
b,
a,
c,
a
)
arrayB is: {(
b,
c,
a
)}
and to sort a mutable array in ascending order you can use NSSortDescriptor and sortUsingDescriptors:sortDescriptors. Also you need to provide the key on the basis of which array will be sorted.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"key" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];
Here you will get what you want.
//sort description will used to sort array.
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"iid" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[arrLeft sortedArrayUsingDescriptors:descriptors];
reverseOrder is your desire output.
there is another way you can sort objects that followed model.
NSArray *someArray = /* however you get an array */
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rank1 = [obj1 valueForKeyPath:#"iid"];
NSNumber *rank2 = [obj2 valueForKeyPath:#"iid"];
return (NSComparisonResult)[rank1 compare:rank2];
}];
here sortedArray is our output.
you can replace same things for yr key as well.
This is what I did to sort the header data in ascending order and to remove duplicates from both header and leftmost column. Hope this will help others
NSOrderedSet *orderedSet3 = [NSOrderedSet orderedSetWithArray:head3];
headData3 = [[orderedSet3 array] mutableCopy];
[headData3 sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2)
{
return [str1 compare:str2 options:(NSNumericSearch)];
}];
NSOrderedSet *orderedSet4 = [NSOrderedSet orderedSetWithArray:left3];
NSMutableArray *arrLeft3 = [[orderedSet4 array] mutableCopy];
[leftTableData3 addObject:arrLeft3];

Trying to store data in an 2d array in objective c

I have code that works but then I would have to add a new array and new code for every new country that my app will support and it is probably highly inefficient, as this code has to be run before the app starts and the view appears.
- (NSMutableDictionary *)retrieveDictionaryOfCountryAndCompany {
NSMutableDictionary *companyAndCountry = [[NSMutableDictionary alloc] init];
NSMutableArray *countryNames = [[NSMutableArray alloc] init];
NSMutableArray *germanyArray = [[NSMutableArray alloc] init];
NSMutableArray *englandArray = [[NSMutableArray alloc] init];
PFQuery *companyQuery = [PFQuery queryWithClassName: #"Company"];
NSArray *objects = [companyQuery findObjects];
for (PFObject *object in objects) {
if ([[object valueForKey:#"country"] isEqual: #"Germany"]) {
[germanyArray addObject:[object valueForKey:#"name"]];
}
[countryNames addObject:[object valueForKey:#"country"]];
}
NSSet *uniqueItems = [NSSet setWithArray:germanyArray];
germanyArray = [[uniqueItems allObjects] mutableCopy];
uniqueItems = [NSSet setWithArray:countryNames];
countryNames = [[uniqueItems allObjects] mutableCopy];
[germanyArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
[countryNames sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
[companyAndCountry setObject:germanyArray forKey:#"Germany"];
[companyAndCountry setObject:countryNames forKey:#"country"];
return companyAndCountry;
}
Is there a better solution that I'm not seeing because it's too simple? Thanks for your help.
Unless I'm being dense:
- (NSMutableDictionary *)retrieveDictionaryOfCountryAndCompany {
NSMutableArray *countryNames = [NSMutableArray array];
NSMutableDictionary *companyAndCountry =
[#{ #"country" : countryNames } mutableCopy];
PFQuery *companyQuery = [PFQuery queryWithClassName: #"Company"];
NSArray *objects = [companyQuery findObjects];
for (PFObject *object in objects) {
NSString *countryName = [object valueForKey:#"country"];
NSString *placeName = [object valueForKey:#"name"];
if(!countryName || !placeName) continue; // a malformed record
[countryNames addObject:countryName];
NSMutableSet *namesInCountry = companyAndCountry[countryName];
if(!namesInCountry)
{
namesInCountry = [NSMutableSet set];
companyAndCountry[countryName] = namesInCountry;
}
[namesInCountry addObject:placeName];
}
for (NSString *key in [[companyAndCountry allKeys] copy])
{
NSArray *sortedArray =
[[companyAndCountry[key] allObjects]
sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)];
companyAndCountry[key] = sortedArray;
}
return companyAndCountry;
}
So just create and populate the lists on demand, initially as sets to avoid some of the array -> set -> array -> sorted array shuffle at the end.
As to performance, Parse is a web service so this should all be done asynchronously. Is that the case?

Remove duplicates from NSArray case insensitively using NSSet

NSArray*arr = #[#"ram",#"Ram",#"vinoth",#"kiran",#"kiran"];
NSSet* uniqueName = [[NSSet alloc]initWithArray:arr];
NSLog(#"Unique Names :%#",uniqueName);
Output:
but i need the output as
You could first convert them all to lowercase strings.
NSArray *arr = #[#"ram",#"Ram",#"vinoth",#"kiran",#"kiran"];
NSArray *lowerCaseArr = [arr valueForKey:#"lowercaseString"];
NSSet* uniqueName = [[NSSet alloc] initWithArray:lowerCaseArr];
NSLog(#"Unique Names :%#",uniqueName);
Unique Names :{(
ram,
kiran,
vinoth
)}
Try this:
NSArray *arr = [NSArray arrayWithObjects:#"Ram",#"ram", nil]; //this is your array
NSMutableArray *arr1 = [[NSMutableArray alloc]init]; //make a nsmutableArray
for (int i = 0; i<[arr count]; i++) {
[arr1 addObject:[[arr objectAtIndex:i]lowercaseString]];
}
NSSet *set = [NSSet setWithArray:(NSArray*)arr1];//this set has unique values
This will always preserve casing form that was existing in your original container (although it's undefined which casing):
NSArray<NSString*>* input = ...
NSMutableDictionary* tmp = [[NSMutableDictionary alloc] init];
for (NSString* s in input) {
[tmp setObject:s forKey:[s lowercaseString]];
}
return [tmp allValues];
Create a mutable array the same size as arr. Fill it with lowercaseString versions of each element of arr. Make the set out of that.
#Updated
Using this you remove uppercase string from your array.
NSMutableArray *arr= [[NSMutableArray alloc]initWithObjects:#"ram",#"Ram",#"vinoth",#"kiran", nil];
NSMutableArray *arrCopy = [[NSMutableArray alloc]init];
for (int index = 0 ; index<arr.count; index++) {
NSUInteger count = [[[[arr objectAtIndex:index] componentsSeparatedByCharactersInSet:[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet]] componentsJoinedByString:#""] length];
if (count == 0) {
[arrCopy addObject:[arr objectAtIndex:index]];
}
}
NSLog(#"Print Mutable Copy %#",arrCopy);
try this one
NSArray *copyArray = [mainArray copy];
NSInteger index = [copyArray count] - 1;
for (id object in [copyArray reverseObjectEnumerator]) {
if ([mainArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
[mainArray removeObjectAtIndex:index];
}
index--;
}
copyArray=nil;

Accessing NSString within NSMutableArray

Why can I not access the 4th element of an NSMutableArray when I initialise with a NSString object rather than input the text manually?
For Example:
NSString * d = #"d";
self.arr = [[NSMutableArray alloc] initWithObjects:
[NSMutableArray arrayWithObjects:#"A",#"B",#"C",d,nil],
[NSMutableArray arrayWithObjects:#"A",#"B",#"C",#"d",nil],
nil];
This causes a beyond bounds error (NSString):
NSMutableArray *subArray = [self.arr objectAtIndex:0];
question = [subArray objectAtIndex:3];
This doesn't (#"d"):
NSMutableArray *subArray = [self.arr objectAtIndex:1];
question = [subArray objectAtIndex:3];
Why does this happen? Surely they are the same thing? I was hoping to reduce the amount of times I would have to write #"d".
They should be same... i tried following in my project. it works well.
NSString * d = #"d";
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
[NSMutableArray arrayWithObjects:#"A",#"B",#"C",d,nil],
[NSMutableArray arrayWithObjects:#"A",#"B",#"C",#"d",nil],
nil];
NSLog(#"0 array 4th:%#",[[array objectAtIndex:0] objectAtIndex:3]);
NSLog(#"1 array 4th:%#",[[array objectAtIndex:1] objectAtIndex:3]);
output is as followings:
2013-12-16 17:05:30.092 Demo[1005:60b] 0 array 4th:d
2013-12-16 17:05:30.094 Demo[1005:60b] 1 array 4th:d

iOS filter an array with an array

I have an array of strings that I want to use as the filter for another array of dictionaries that is created from a plist. For example, if I had a plist of dictionaries that looked like so:
Key: Value:
car1 audi
car2 bmw
car3 bmw
car4 audi
car5 jaguar
and my array of strings was "audi, jaguar". How would I code it so that I can create a new array that would return "car1, car4, car5"? Hope this makes sense. Or better yet, how can I walk down this dictionary and filter it based on a value and then create a new array of dictionaries to use.
Code:
-(void)plotStationAnnotations {
desiredDepartments = [[NSMutableArray alloc] init];
BOOL tvfrSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"tvfrSwitchStatus"];
BOOL hfdSwitchStatus = [[NSUserDefaults standardUserDefaults] boolForKey:#"hfdSwitchStatus"];
if (tvfrSwitchStatus) {
NSString *tvfr = #"TVF&R";
[desiredDepartments addObject:tvfr];
}
if (hfdSwitchStatus) {
NSString *hfd = #"HFD";
[desiredDepartments addObject:hfd];
}
NSLog(#"Array 1 = %#", desiredDepartments);
NSString *path = [[NSBundle mainBundle] pathForResource:#"stationAnnotations" ofType:#"plist"];
NSMutableArray *anns = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSMutableArray *newDictionaryArray = [NSMutableArray array];
for (NSDictionary *dictionary in anns) {
for (NSString *string in desiredDepartments) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}
NSLog(#"Array = %#", keyMutableArray);
for (int i = 0; i < [keyMutableArray count]; i++) {
float realLatitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"latitude"] floatValue];
float realLongitude = [[[keyMutableArray objectAtIndex:i] objectForKey:#"longitude"] floatValue];
StationAnnotations *myAnnotation = [[StationAnnotations alloc] init];
CLLocationCoordinate2D theCoordinate;
theCoordinate.latitude = realLatitude;
theCoordinate.longitude = realLongitude;
myAnnotation.coordinate = theCoordinate;
myAnnotation.title = [[keyMutableArray objectAtIndex:i] objectForKey:#"station"];
myAnnotation.subtitle = [[keyMutableArray objectAtIndex:i] objectForKey:#"department"];
[mapView addAnnotation:myAnnotation];
}
}
May be something like
NSArray *array1;
if([array1 containsObject : someValue])
can help. someValue can be your values you want to check if they exist in array1.
You can do something like this to filter by keys:
NSArray *keysToLookFor = [NSArray arrayWithObjects:#"car1", #"car4", #"car5", nil];
NSArray *foundObjects = [dictionary objectsForKeys:keysToLookFor notFoundMarker:nil];
Or something like this to filter by values:
NSString *valueToLookFor = #"Audi";
NSArray *keyArray = [dictionary allKeysForObject:valueToLookFor];
// To filter by multiple values
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
NSMutableArray *keyMutableArray = [NSMutableArray array];
for (NSString *string in valuesToFilterBy) {
[keyMutableArray addObjectsFromArray:[dictionary allKeysForObject:string]];
}
Updated answer for dictionaries in arrays:
NSArray *dictionaryArray; // The array of dictionaries that you have
NSMutableArray *newDictionaryArray = [NSMutableArray array];
NSArray *valuesToFilterBy = [NSArray arrayWithObjects:#"Bmw", #"Audi", nil];
for (NSDictionary *dictionary in dictionaryArray) {
for (NSString *string in valuesToFilterBy) {
if ([dictionary allKeysForObject:string]) {
[newDictionaryArray addObject:dictionary];
break;
}
}
}

Resources