fill NSArray from NSDictionary - ios

I'm new to Objective-C, and I would like to know how I can fill my NSArray from a NSDictionary ?
My NSDictionary look like this :
user = {
items = (
{
nom = nom1;
prenom = prenom1;
},
{
nom = nom2;
prenom = prenom2;
},
{
nom = nom3;
prenom = prenom3;
}
);
};
It is based on a Json, and I want my array to be like :
"prenom1.nom1", "prenom2.nom2", "prenom3.nom3"
I've tried something like this
array = [self.users objectForKey:#"user"]
but the result is the same as in my dictionary.

You can use enumerateObjectsUsingBlock -
NSArray *itemsArray=[user objectForKey:#"items"];
NSMutableArray *outputArray=[[NSMutableArray alloc]init];
[itemsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[outputArray addObject:[NSString stringWithFormat:#"%#.%#",[obj objectForKey:#"prenom"],[obj objectForKey:#"nom"]]];
}];
outputArray will contain your names in the required format

NSDictionary *users = // your dictionary
NSArray *items = users[#"items"];
NSMutableArray *names = [NSMutableArray array];
for (NSDictionary *item in items) {
NSString *name = [NSString stringWithFormat:#"%#.%#", item[#"prenom"], item[#"nom"]];
[names addObject:name];
}
Using the dictionary you supplied this will add all the names in the format you wanted to the names array.

Related

how to remove duplicates from array of dictionary for a specific key

{
distance = "0.03159804520191554";
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824706065;
uuid = "1838346268_374823983610_2016-08-08T07:32:22.680GMT";
}
This is what I got from the array of dictionaries. I want to remove duplicates where rid=374824705969 without using loops.Can any one help me.
Thanks in advance.
Try these one:
NSArray *array = #[
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824705969,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
},
#{
#"rid" : #374824706065,
#"uuid" : #"1838346268_374823983610_2016-08-08T07:32:22.680GMT"
}];
NSMutableSet *keys = [NSMutableSet new];
NSMutableArray *result = [NSMutableArray new];
for (NSDictionary *data in array) {
NSString *key = data[#"rid"];
if ([keys containsObject:key]) {
continue;
}
[keys addObject:key];
[result addObject:data];
}
NSLog(#"%#", result);

Convert NSString into NSDIctionary

I have a string ------ NSString abc = #"apple:87,banana:32,grapes:54";
i need this output like this
{
name = "apple";
value = "87";
},
{
name = "banana";
value = "32";
},
{
name = "grapes";
value = "54";
}
I have tried:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (NSString* item in itemList) {
NSArray* subItemList = [item componentsSeparatedByString:#":"];
if (subItemList.count > 0) {
[dict setObject:[subItemList objectAtIndex:1] forKey:[subItemList objectAtIndex:0]];
}
}
NSLog(#"%#", dict);
The output is --
{
apple = 87;
banana = 32;
grapes = 54;
}
but i dont want this output
The wanted output is a NSArray of NSDictionary.
So:
NSArray* itemList = [abc componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (NSString *aString in itemList)
{
NSArray* subItem = [aString componentsSeparatedByString:#":"];
NSDictionary *dict = #{#"name":[subItem objectAtIndex:0],
#"value":[subItem objectAtIndex:1]};
[finalArray addObject:dict];
}
I didn't use the if ([subItem count] > 0), trying just to keep the logic you missed and clarify the algorithm.
I didn't test the code, but that should do it. (or maybe a little compiler error easy to correct).
In case anyone wants the equivalent in Swift:
let abc = "apple:87,banana:32,grapes:54"
let dict = abc.componentsSeparatedByString(",").map { pair -> [String: String] in
let parts = pair.componentsSeparatedByString(":")
return ["name": parts[0], "value": parts[1]]
}

NSDictionary order does not match allKeys order

I've created NSDictionary of sorted arrays by name organized by first letter (see results below). When I use the command allKeys for that same Dictionary, the order is not the same. I need the order the same because this NSDictionary is used in UITableview and should be alphabetical.
- (NSDictionary*) dictionaryNames {
NSDictionary *dictionary;
NSMutableArray *objects = [[NSMutableArray alloc] init];
NSArray *letters = self.exhibitorFirstLetter;
NSArray *names = self.exhibitorName;
for (NSInteger i = 0; i < [self.exhibitorFirstLetter count]; i++)
{
[objects addObject:[[NSMutableArray alloc] init]];
}
dictionary = [[NSDictionary alloc] initWithObjects: objects forKeys:letters];
for (NSString *name in names) {
NSString *firstLetter = [name substringToIndex:1];
for (NSString *letter in letters) { //z, b
if ([firstLetter isEqualToString:letter]) {
NSMutableArray *currentObjects = [dictionary objectForKey:letter];
[currentObjects addObject:name];
}
}
}
NSLog(#"%#", dictionary);
NSLog(#"%#", [dictionary allKeys]);
return dictionary;
}
B = (
"Baker's Drilling",
"Brown Drilling"
);
C = (
"Casper Drilling"
);
J = (
"J's, LLC"
);
N = (
"Nelson Cleaning",
"North's Drilling"
);
T = (
"Tim's Trucks"
);
Z = (
"Zach's Main",
"Zeb's Service",
"Zen's"
);
}
J,
T,
B,
N,
Z,
C
)
NSDictionary is not an ordered collection. There's no way to control how it orders things, and it may change completely depending on OS version, device type, and dictionary contents.
I just put the NSDictionary in sorted array:
- (NSArray*)sortAllKeys:(NSArray*)passedArray{
NSArray* performSortOnKeys = [passedArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
return performSortOnKeys;
}

NSString subsstring

I have a string like this
12,23,45,3,12,
What I want to do is get this each number and check with an array value. How I can get each value as a substring to check
Thanks
Break this string to array.
NSString *string = #"12,23,45,3,12,";
NSArray *array = [string componentsSeparatedByString:#","];
Then you can compare with the array.
EDIT :
As per your comment that you want to check all the string values to be present in main-other-array.
NSString *string = #"12,23,45,3,12";
NSArray *array = [string componentsSeparatedByString:#","];
//below is the main-other-array
NSArray *toCheckArray = #[#"124",#"23",#"45",#"3",#"12",#"1000"];
BOOL arrayIsContainedInToCheckArray = YES;
for (NSString *arrayObj in array) {
if (![toCheckArray containsObject:arrayObj]) {
arrayIsContainedInToCheckArray = NO;
}
}
NSLog(#"%#",arrayIsContainedInToCheckArray?#"All exist":#"All doesn't exist");
May be it helps you :
NSString *str = #"12,23,45,3,12";
NSArray *strArray = [str componentsSeparatedByString:#","];
NSArray * anotherArray = nil; // have some value
for (NSString * value in strArray)
{
int intVal = [value integerValue]; // here is your separate value
for (int i = 0; i < [anotherArray count]; i++) // You can check against another array
{
id anotherVal = [anotherArray objectAtIndex:i];
// Here you can check intVal and anotherVal from another array
}
}
Use this, It will help you..
NSArray *detailArray = [yourString componentsSeparatedByString:#","];

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