I have an array that I am filling with boolean values in the following code.
for(int i = 0; i < 15; i++){
int checkVal = [(NSNumber *)[__diceValue objectAtIndex:i] intValue];
if(checkVal == matchVal){
[_diceMatch replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:y]];
}
}
Whats the shortest way to write a conditional to check the array "_diceMatch" for all true values?
If your array can only contain the values "true" (#YES) or "false" (#NO)
then you can simply check for the absence of #NO:
if (![_diceMatch containsObject:#NO]) {
// all elements are "true"
}
NSUInteger numberOfTrueValues = 0;
for (NSNumber *value in _diceMatch) {
if ([value boolValue]) {
numberOfTrueValues++;
}
}
Shortest way? maybe not. Easiest way? Yes
- (BOOL)isDictMatchAllTrue {
for (NSNumber *n in _dictMatch) {
if (![n boolValue]) return NO;
}
return YES;
}
or you don't like writing loop
NSSet *set = [NSSet setWithArray:_diceMatch];
return set.count == 1 && [[set anyObject] boolValue];
Note: first version return YES when array is empty but second version return NO.
You can add
if (_dictMatch.count == 0) return YES; //or NO
to fix it.
Related
Can't understand that the object is nil:
if ([self indexFromObjectProperty:UUID])
{}
else
{}
The problem is that indexFromObjectProperty can be 0 but I need to check the situation when there is no such element in array.
-(NSInteger)indexFromObjectProperty:(NSString *)property
{
NSInteger iIndex;
for (int i = 0; i < [items count]; i++)
{
if([property isEqualToString:[[items objectAtIndex:i] objectForKey:#"UUID"]])
{
iIndex = i;
}
}
return iIndex;
}
How can I solve this?
To your Q: You can initialize iIndex with NSNotFound. Then you compare to it.
Additionally: NSPredicate (and some other suggestions leading too far away from the Q.)
When you create the iIndex, set the value to some default:
NSInteger iIndex = NSNotFound;
Then you can check it in your if:
if ([self indexFromObjectProperty:UUID] != NSNotFound)
I have a Card object, that has a flag isFlipped. I store them in a NSMutableArray. I want to check if two objects in my array have the flag on, and if they do, I remove them.
As far as I understand I need to iterate over array, but how do I get another object with a flag?
- (void) checkCards
{
for (Card *card in cards) {
if (card.flipped)
{
if ( ??? )
{
}
}
}
}
Store the index of the cards that you want to remove in variables and if the value of both the variables are set then just remove the cards. See the following
- (void) checkCards {
int card1 = -1;
int card2 = -1;
for(int i = 0; i < [cards count]; i++) {
Card *card = [cards objectAtIndex: i];
if(card.flipped) {
if(card1 == -1) {
card1 = i;
} else {
card2 = i;
}
if(card1 != -1 && card2 != -1) {
// remove cards
break;
}
}
}
}
I would use the NSArray method, indexesOfObjectsPassingTest:. You can use it like this:
NSIndexSet *indexSet = [cards indexesOfObjectsPassingTest:^BOOL (Card *obj, NSUInteger idx, BOOL *stop) {
return obj.isFlipped = YES;
}];
[cards removeObjectsAtIndexes:indexSet];
This will remove all cards, whose isFlipped is YES, so if there could be more than 2, and you only want to remove 2, then you would have to iterate through the indexSet and stop after removing 2.
I have an array of dictionaries that I would like to go through to find a matching value that I can then Count == Nth item of the array
Each item of the array looks like this
HMOD = 0;
MID = 39;
MOD = SOMETHING; // looking for this value
ID = 50;
So I would like to create a loop that goes through the array until it finds the matching value, then I use the number in the count as an reference to Index path in the next view..
I have written this peice of code which dosnt work... but hopefully it gives you an idea of the loop I am trying to create.
int count = 0;
while (singleName != [[ModArray valueForKey:#"MOD"] objectAtIndex:count]) {
count ++;
NSLog(#"%i", count);
}
SingleName is a NSString that I am using to match the MOD value in ModArray...
Any help would be greatly appreciated.
Here is a simpler solution by using valueForKey on the array of dictionaries,
Assuming that your modArray is like this,
NSArray *modArray = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObject:#"0" forKey:#"HMOD"],
[NSDictionary dictionaryWithObject:#"39" forKey:#"MID"],
[NSDictionary dictionaryWithObject:#"something" forKey:#"MOD"],
[NSDictionary dictionaryWithObject:#"50" forKey:#"ID"], nil];
And singleName has a value as "something"
NSString *singleName = #"something";
Fetch the array from modArray which has an object with key as "MOD",
NSArray *array = [modArray valueForKey:#"MOD"];
Check if singleName is present in this array. If yes, then get the first index of that object which will be same as the index of dictionary with key "MOD" in modArray.
if ([array containsObject:singleName]) {
NSLog(#"%d", [array indexOfObject:singleName]);
} else {
NSLog(#"%# is not present in the array", singleName);
}
Update:
If you want to do it in your way, only mistake was you were using != whereas you should have used isEqualToString. You should have done like this,
int count = 0;
while (![singleName isEqualToString:[[modArray valueForKey:#"MOD"] objectAtIndex:count]]) {
count ++;
NSLog(#"%i", count);
}
Your code looks all inside out. You state you have an array of dictionaries. Assuming ModArray is the array (based on the name) you might do this:
NSUInteger count = 0;
for (NSDictionary *dict in ModArray) { // iterate through the array
NSString *mod = dict[#"MOD"]; // get the value for MOD
if ([mod isEqualToString:singleName]) { // compare the two strings
break; // they match so exit the loop
}
count++
}
// count has the index of the dictionary with the matching MOD value
Edit: Based on ACB correcting my misunderstanding of NSArray valueForKey:, the only real issue is your use of using != to compare the two strings.
- This is Helpful when you search from Dictionary.
NSMutableArray *contentList;
NSMutableArray *filteredContentList;
BOOL isSearching;
// firstSection is array which already filled.
// contentList array for value of particular key
// filteredContentList is search array from actual array.
- (void)searchTableList {
NSString *searchString = searchBar.text;
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:#"frame_code beginswith[c] %#", searchString];
NSArray *filteredArr = [firstSection filteredArrayUsingPredicate:filterPredicate];
if(contentList.count > 0)
[contentList removeAllObjects];
[filteredContentList addObjectsFromArray:filteredArr];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar1 {
if ([searchBar1.text length] != 0)
isSearching = YES;
else
isSearching = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
[tblFrameList_SComplete reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
I'm trying to store numbers in a NSMutableArray, but when I check it, all I get is garbage.
-(void)storeIntoArray:(int)indexInt
{
NSNumber *indexNum = [[NSNumber alloc] initWithInt:indexInt];
[last100 insertObject:indexNum atIndex:prevCount];
prevCount++;
if(prevCount > 100)
{
prevCount = 0;
cycledOnce = YES;
}
}
-(BOOL)checkArray:(int)indexInt
{
for(int i = 0;i < [last100 count];i++)
{
NSLog(#"Stored: %d",[last100 objectAtIndex:i]);
if (indexInt == (int)[last100 objectAtIndex:i]) {
NSLog(#"Same entry, trying again");
return YES;
}
}
return NO;
}
When I check, I'll get values back like Stored: 110577680 and just various garbage values.
You're printing the NSNumber object address, not its value. Try using intValue. Or, if you want to print the object directly, use %# rather than %d.
NSLog(#"Stored: %d",[last100 objectAtIndex:i]);
Should be:
NSLog(#"Stored: %#",[last100 objectAtIndex:i]);
NSNumber is an object not an integer.
I would like to know how to compare a string with an array, i.e., if my array list has {"abc", "pqr", "xyz"} and the new string lets say "mno" is typed, it should compare with my previous array list. How can I do this? Thanks in advance.
Look at the NSArray documentation...
BOOL hasString = [your_array containsObject:your_string];
System:
if ([yourArray containsObject:yourNSString])
{
NSLog(#"Bingo!");
}
Manual:
for (int i = 0 ; i < [yourArray count] ; i++) {
if ([yourNSString isEqualToString:[yourArray objectAtIndex:i]]) {
NSLog(#"Bingo!");
break;
}
}
for(int i=0; i<[myarray length]; ++i) {
if([myarray[i] isEqualToString:#"mno"])
NSLog("Equal");
else NSLog("Not Equal");
}
Here is a working (tested) method,
-(BOOL)checkStingInArray: (NSString *)aString arrayWithStrings:(NSMutableArray *)array
{
if ( [array containsObject: aString] ) {
NSLog(#" %# found in Array",aString );
return YES;
} else {
NSLog(#" %# not found in Array",aString );
return NO;
}
}