How to search through a NSMutableArray - iphone

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.

Related

Unable to save array to NSUserDefaults

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.

adding Key values from NSDictionary to NSarray

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.

Check whether dictionary is present in array of Dictionaries?

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.

Three20: Extracting NSArray from userinfo

I have been using Grinich's method of using the userinfo category for passing on objects, in which case I'm passing an array of FeedItem class objects. However, modelItems as well as feedItems return a null even when myPassedObject is able to print my items when i NSLog it.
id myPassedObject = [query objectForKey:#"__userInfo__"];
NSArray *modelItems = myPassedObject;
for (FeedItem *feedItem in modelItems) {
[feedItems addObject:feedItem];
}
Try casting myPassedObject to an NSArray when you assign it to modelItems. Doesn't seem to be anything else wrong.
I would print out or inspect the query dictionary to ensure that you are passing myPassedObject in correctly.

Objective C: Compare Array Element to String

Greetings,
I'm trying to simply compare a NSString to an NSArray.
Here is my code:
NSString *username=uname.text;
NSString *regex=#"^[a-zA-Z0-9-_.]{3,20}$";
NSArray *matchArray=nil;
matchArray=[username componentsMatchedByRegex:regex];
if(matchArray[0] == "asdf"){ //this line causes the problem!
NSLog(#"matchArray %#",matchArray);
}
I get an "invalid operands to binary ==" error.
How can I compare the string?
Many thanks in advance,
You are trying to compare an NSString to a C string (char *), which is wrong. matchArray is an NSArray so you cannot treat it as a C array either, you have to use its objectAtIndex: method and pass in the index.
Use this instead:
if ([[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
Addressing your comments, the reason why isEqualToString: does not show up in autocomplete is because Xcode cannot guess that matchArray contains NSStrings (it only knows it contains ids, that is, arbitrary Objective-C objects). If you really wanted to be sure, you can perform an explicit cast, but it doesn't matter if you don't:
if ([(NSString *)[matchArray objectAtIndex:0] isEqualToString:#"asdf"]) {
NSLog(#"matchArray %#", matchArray);
}
you want to use -objectAtIndex to get the array element. NOT the C array accessor syntax
try to use:
[[matchArray objectAtIndex:0] isEqualToString:#"asdf"];
anyway the string "asdf" should be #"asdf"