I want to add all the keys from the dictionary to the array. This is what I am doing right now.As code below:
for (NSString * akey in _groups ) {
NSLog(#"%#",akey);
[_groupArray addObject:akey];
NSLog(#"%#",_groupArray);
}
The log is showing Null for _groupArray. I even tried using insertObjectAtIndex even that does not work.Not sure what I am doing wrong and yes I am getting the keys in the dictionary (_groups) nothing wrong with that.
You should initialize the array before starting to add values to it. Otherwise it is initially nil and will remain nil.
You can use allKeys to get all the keys of the array. But since _groupArray is an NSMutableArray, you have to do that like this:
_groupArray = [NSMutableArray arrayWithArray:[_groups allKeys]];
Or:
_groupArray = [[_groups allKeys] mutableCopy];
If _groupsArray is new or empty anyway then you can use
_gropusArray = [NSMutableArray arrayWithArray:[dict allKeys]];
That should release you from the compiler warning.
If _groupsArray was not empty before and you need to addValues then go for:
[_groupsArray addObjectsFromArray:[dict allKeys]];
this is how you should do it....
_groupsArray=[dict allKeys];
don't forget to allocate memory to your _groupsArray.. :)
Have you checked you've alloc'd and init'd your mutable array. Unless there's already stuff in it that you're adding to - and even then - consider using the NSDictiomary allKeys method rather than iterating through the dictionary.
From the docs
allKeys
Returns a new array containing the dictionary’s keys.
- (NSArray *) allKeys
Return Value
A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.
Discussion
The order of the elements in the array is not defined.
Related
This is my first attempt at using NSUserDefaults. I've read every question & answer posted in stackoverflow regarding this subject, but still can't get it to work. I must be missing something basic. The array (allContacts) merely contains a few names and phone numbers. Unless I'm misunderstanding what's happening, both fields are NSStrings. Or are they just pointers to strings? If that's the case, how would I convert them to actual NSStrings? Here's my code to save the array:
- (BOOL)saveChanges
{
NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:allContacts];
[[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:#"allContacts"];
[[NSUserDefaults standardUserDefaults] synchronize];
return 1;
}
Here my log:
2013-08-07 15:48:17.568 ImOK[5515:907] *** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
"Brad Pitt, 1-917-297-1234",
"Marilyn Monroe, 9179291234"
)' of class '__NSArrayM'. Note that dictionaries and arrays in property lists must also contain only property values.
Thanks in advance for any help.
This code "for(id contact in allContacts) { NSLog(#"%#", [contact class]); }" gives me:
2013-08-07 17:11:30.845 ImOK[5569:907] Contacts
2013-08-07 17:11:30.854 ImOK[5569:907] Contacts
so I guess they are not valid property values.
Incidentally, there was no intelligent reason for me to attempt to save the array as an NSMutableArray. I was just experimenting.
From the Apple documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSUserDefaults
A default object must be a property list, that is, an instance of (or
for collections a combination of instances of): NSData, NSString,
NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any
other type of object, you should typically archive it to create an
instance of NSData.
If allContacts is an NSArray, just use that in your setObject:forKey: call. If it's an NSMutableArray, use:
[allContacts copy]
to get a non-mutable copy of the array.
I have an array of dictionaries which contains Same keys but different values.
I have another dictionary and i want to check whether this dictionary is present in that array or not…???
suppose you have three keys in your sesond dictionary key1,key2,key3 so to get verification of presence of the dictionay in ayour array use 'NSPredicate` class like this
Suppose your array is _myDicArray and other dictionary is _refDic
NSPredicate* myPredicate =[NSPredicate predicateWithFormat:#"key1 like %# AND key2 like %# AND key3 like %#",[_refDic objectForKey:#"key1"],[_refDic objectForKey:#"key2"],[_refDic objectForKey:#"key3"]];
NSArray* someOtherArr = [[_myDicArray filteredArrayUsingPredicate:filmPredicate] objectAtIndex:0];
if([someOtherArr count] > 0)
//this is what you wanted ... this array has ur dic
I think this should also work
NSPredicate* myPredicate =[NSPredicate predicateWithFormat:#"self == %#",_refDic];
NSArray* someOtherArr = [[_myDicArray filteredArrayUsingPredicate:filmPredicate] objectAtIndex:0];
if([someOtherArr count] > 0)
//this is what you wanted ... this array has ur dic
Well, I would implement it this way.
Create a subclass of NSDictionary and implement these methods:
- (BOOL)isEqual:(id)object;
- (NSUInteger)hash;
It's very important that you properly implement hash. It should return different values for different dictionaries even if they are equal according to your definition. In isEqual you can check if both dictionaries contain the same keys and the same values. If yes, return YES, otherwise return NO.
With this your check is later merely one line: [arrayOfDictionaries containsObject:dictionaryIAmLookingFor];
If you implement improperly hash or skip implementing it, containsObject will not execute isEqual on all the objects in the array.
I have a NSMutableArray that I need to search for a string and return the key in the array where the string was found. So for example if I'm searching "ipod" and it's the 4th in the array, it would return 3 or whatever position the string is in. What's the best way to do this?
return [theArray indexOfObject:#"ipod"];
Reference: http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/indexOfObject:.
Note that NSMutableArray inherits from NSArray, so any NSArray methods can be used on NSMutableArray too.
Again from the documentation:
Index of Object Passing test
You'll have to write a code block that tests for the substring in each object: NSString rangeOfString: options:
Then you'll get the index of the object with the substring. You'll need to run the string search again for your result, but that should get you what you are after.
I need an NSDictionary which has key in the form of string (#"key1", #"key2") and value in the form of a C-style two-dimensional array (valueArray1,valueArray2) where valueArray1 is defined as :
int valueArray1[8][3] = { {25,10,65},{50,30,75},{60,45,80},{75,60,10},
{10,70,80},{90,30,80},{20,15,90},{20,20,15} };
And same for valueArray2.
My aim is given an NSString i need to fetch the corresponding two-dimensional array.
I guess using an NSArray, instead of c-style array, will work but then i cannot initialize the arrays as done above (i have many such arrays). If, however, that is doable please let me know how.
Currently the following is giving a warning "Passing argument 1 of 'dictionaryWithObjectsAndKeys:' from incompatible pointer type" :
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:valueArray1,#"key1",
valueArray2,#"key2",nil];
Is valueArray2 also an int[][3]? If so, you could use
[NSValue valueWithPointer:valueArray1]
to convert the array into an ObjC value. To retrieve the content, you need to use
void* valuePtr = [[myDict objectForKey:#"key1"] pointerValue];
int(*valueArr)[3] = valuePtr;
// use valueArr as valueArrayX.
If there's just 2 keys, it is more efficient to use a function like
int(*getMyValueArr(NSString* key))[3] {
if ([key isEqualToString:#"key1"]) return valueArray1;
else return valueArray2;
}
Rather than Adding Array Directly as a value in NSDictionary make a custom class in which create variable of NSArray ... and set this class object as value like
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:MyClassObj1,#"key1",
MyClassObj2,#"key2",nil];
where MyClassObj1 and MyClassObj2 are member of MyClass
I have a dictionary of dictionaries and I have retrieved from a plist.
Suppose the high hierarchy dictionary is COUNTRIES and each sub dictionary is a COUNTRY.
Each COUNTRY sub dictionary has keys like name, currency, population, flag, etc.
After retrieving the dictionary and its subs to a variable as in
NSMutableDictionary * countries = [NSMutableDictionary dictionaryWithContentsOfFile:path];
How do I check to see if a currency named "euros" is present there?
I mean, I am checking for a value in a key of a subdictionary... is it possible? How?
thanks in advance.
NOTE: It is a dictionary inside a dictionary, not an array inside a dictionary or a dictionary inside an array. Each sub dictionary is store inside the main dictionary using a number. So, inside sub dictionary #1 may be a dictionary which keys are, for example, France, euros, 30 million people.
I need to see if France sub dictionary is present inside the main dictionary.
Use this to get any countries with a currency named "Euro" (in an NSArray).
NSArray *allCountries = [countries allValues];
NSPredicate *euroPredicate = [NSPredicate predicateWithFormat:#"currency == %#", #"Euro"];
NSArray *filteredCountries = [allCountries filteredArrayWithPredicate:euroPredicate];
If all you need to do is check whether such a country exists, then you can just do a simple if (filteredCountries.count > 0) { }.
Sidenote: I don't see a reason for the top data structure to be an NSDictionary if the country name is also stored in the inner NSDictionary (presumably the country name is the outer dictionary key) - perhaps an NSArray as the outer structure would be more appropriate?
NSDictionary *_currencyDict = [countries objectForKey:#"currency"];
NSArray *_currencies = [_currencyDict allValues];
NSPredicate *_currencyPredicate = [NSPredicate predicateWithFormat:#"SELF IN %#", _currencies];
BOOL _eurosResult = [_currencyPredicate evaluateWithObject:#"euros"];
if (_eurosResult)
NSLog(#"The value 'euros' is in the 'currency' dictionary, within the 'countries' dictionary.");
else
NSLog(#"The value 'euros' was not found.");