Obj-C, function to return index of nsstring found in nsarray? - objective-c

I've been looking to see if I can find a function like indexOf.
I have an array.
self.data = [[NSArray alloc] initWithObjects:#"apple", #"lemon", #"pear", nil];
Looking for a function to return which would look for lemon and return 1 ?

how about indexOfObject:?
NSUInteger index = [self.data indexOfObject:#"lemon"];

Try this method.
-(int)indexOfString:(NSString *)string inArray:(NSArray *)array {
for(int i=0; i<[array count]; i++) {
if ([[array objectAtIndex:i] class] == [NSString class]) {
if ([[array objectAtIndex:i] isEqualToString:string]) {
return i;
}
}
}
}
EDIT: The other answer using -indexOfObject: is better.

Related

Find a dictionary in ArrayOfDictionaries with a specific keyvalue pair

I have an array of dictionaries
for(int i = 0; i < 5; i++) {
NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionary];
[_myDictionary setObject:[NSString stringWithFormat:#"%d",i] forKey:#"id"];
[_myDictionary setObject:label.text #"Name"];
[_myDictionary setObject:label1.text #"Contact"];
[_myDictionary setObject:label2.text #"Gender"];
}
[_myArray addObject:_myDictionary];
Now I want to pick a dictionary from the array whose objectForKey:#"id" is 1 or 2 or something else like there is an sql query Select * from Table where id = 2.
I know this process
int index = [_myArray count];
for(int i = 0; i < 5; i++)
{
NSMutableDictionary *_myDictionary = [NSMutableDictionary dictionaryWithDictionary:[_myArray objectAtIndex:i]];
if([[_myDictionary objectForKey:#"id"] isEqualToString:id])
{
index = i;
return;
}
}
if(index != [_myArray count])
NSLog(#"index found - %i",index);
else
NSLog(#"index not found");
Any help would be appreciated.
Thanks in Advance !!!
Try this, this is by using fast enumeration
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for(dict in _myArray)
{
if([[dict valueForKey:#"id"] isEqualToString:#"1"])
{
return;
}
}
You should use [NSNumber numberWithInteger: i] not a NSString.
Code fore this search should look like this:
NSString *valueToFind = [NSString stringWithFormat:#"%d", intValue]; // [NSNumber numberWithInteger: intValue]
NSInteger index = [_myArray indexOfObjectPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
return [valueToFind isEqualToString: [obj objectForKey: #"id"]];
}];
NSDitionary *found = [_myArray objectAtIndex: index];

NSMutableArray to NSString conversion

Here is the string from NSMutableArray:
(
(
"Some String Value"
)
)
This code displays the string value that I want, but however, it displays with the brackets and quotes. How do I remove them?
Thank you in advance!!
In your case it is 2D Array:
Something like this:
NSArray *arr=[NSArray arrayWithObject:#"asdf"];
NSArray *arr2=[NSArray arrayWithObjects:arr, nil];
You need to go to 2nd level to retrive it as :
NSLog(#"=> %#",arr2[0][0]);
NSString *string=arr2[0][0];
-(void)repeatArray:(NSArray *)array1
{
static NSMutableString *InsideString; // Better to use global Varaible declared in ViewDidLoad/loadView
NSArray *array = array1; //Its your array
for (int i = 0; i< [array count]; i++) {
if ([[array objectAtIndex:i] isKindOfClass:[NSArray class]]) {
[self repeatArray:[array objectAtIndex:i]];
} else if ([[array objectAtIndex:i] isKindOfClass:[NSString class]]) {
[InsideString appendString:[NSString stringWithFormat:#"%# ", [array objectAtIndex:i]]];
}
}
}

Get the correct index of dictionary

NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
NSLog(#"The content of array is%#",tmpMutArr);
int index;
for (int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:[NSString stringWithFormat:#"%#", nameString]])
{
index = i;
}
}
}
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
This code is not replacing the matching object in tmpMutArr as I want it to, but replaces all objects in tmpMutArr instead. How to replace only the index I want?
I know that tmpMutArr containing all objects before the replacement, so I just need to specify the index correctly I think. How to do so?
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
NSLog(#"The content of array is%#",tmpMutArr);
int index;
for (int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:nameString])
{
index = i;
break; // << added break
}
}
}
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
maybe, you should try to this version... you have not specified which index is needed, I suppose the first one.
for (int i=0;i<[tmpMutArr count];i++) {
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:[NSString stringWithFormat:#"%#", nameString]]) {
index = i;
break; // when you find the first one, you should go out from the iteration
}
}
}

out of range in objectAtIndex objective c

The count of children_ (CCArray) outputs 15 and I'm receiving error:
'NSInternalInconsistencyException', reason: 'index out of range in objectAtIndex(14), index 15'
for (NSInteger i=[children_ count]-1; i>=0; i++) {
CCNode *c = [children_ objectAtIndex:i];
if ([c isKindOfClass:[CCLabelTTF class]]) {
[c removeFromParentAndCleanup:YES];
}
}
How would I solve this? Trying to remove all the labels in order to change their string value.
On my CCLayer I have have also some CCMenuItemLabel and CCMenuItemLabelAndSprite...
It looks like you want to iterate backwards through the collection class, so you need to perform i-- to modify the index variable:
for (NSInteger i=[children_ count]-1; i>=0; i--) {
CCNode *c = [children_ objectAtIndex:i];
if ([c isKindOfClass:[CCLabelTTF class]]) {
[c removeFromParentAndCleanup:YES];
}
}
you should use fast enumerating if possible:
for (id obj in [childres_ reverseObjectEnumerator]){
if ([obj isKindOfClass:[CCLabelTTF class]]) {
[obj removeFromParentAndCleanup:YES];
}
}
or with the block syntax
[children_ enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
if ([obj isKindOfClass:[CCLabelTTF class]]) {
[obj removeFromParentAndCleanup:YES];
stop= YES;
};
}];
It seems that you are initializing your for loop counter with count-1 and incrementing, so the first value of i would be 14 , and the next one 15 (out of range)
Try this :
for (NSInteger i=0; i<[children_ count]; i++) {
}

printing an array of arrays in objective C

Sorry for the simple question, but I am self taught and know that there are gaps in my education.
To print an array in objective C, I believe is:
NSLog(#"My array: %#", myArray);
How can I print an array of arrays?
Thanks
You want this:
for(NSArray *subArray in myArray) {
NSLog(#"Array in myArray: %#",subArray);
}
This will work for an array that has arrays nested one level deep.
You don't need to do anything different to log an array of arrays; the code exactly as you've written it will already show the contents of the sub-arrays.
That is, the following program:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [NSMutableArray array];
for (int i=0; i<5; ++i) {
NSMutableArray *sub = [NSMutableArray array];
for (int j=0; j<=i; ++j) {
[sub addObject:[NSString stringWithFormat:#"%d", j]];
}
[array addObject:sub];
}
NSLog(#"Array: %#", array);
[pool drain];
return 0;
}
Produces the following output:
Array: (
(
0
),
(
0,
1
),
(
0,
1,
2
),
(
0,
1,
2,
3
),
(
0,
1,
2,
3,
4
)
)
Clearly, it's already logging the sub-arrays just fine. If you want to control the formatting differently, you'd have to manually iterate them, but by default, the -description of an NSArray is little more than the -description of every object in that array, which includes all sub-arrays.
So I was embarrassed by the recursiveDescription thing, so I wrote my own as a category on NSArray. Note that this code will print out a description for an array of arrays to any depth. The description itself could probably use a bit more formatting than commas and newlines. Here you go:
#interface NSArray (RecursiveDescription)
- (NSString *)recursiveDescription;
#end
#implementation NSArray (RecursiveDescription)
- (NSString *)recursiveDescription {
NSMutableString *description = [[NSMutableString alloc] initWithString:#"Array (\n"];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (NSObject *child in self) {
if ([child respondsToSelector:#selector(recursiveDescription)]) {
[description appendFormat:#"%#,\n", [child recursiveDescription]];
}
else {
[description appendFormat:#"%#,\n", [child description]];
}
}
[pool drain];
[description appendString:#"\n)"];
return [description autorelease];
}
#end
Try logging the return value from NSArray's -description method.
NSLog(#"My array: %#", [myArray description]);
Moreover, for print all of elements
int i = 0;
int j = 0;
for(NSArray *subArray in myArray) {
NSLog(#"[%d] %#",i, subArray);
j =0;
for(NSObject *element in subArray) {
NSLog(#"[%d:%d] %#", i,j,element);
++j;
}
++i;
}
As much as I like how easy it is to log out an object in Objective-C, I didn't like seeing a 2D array as a very long list. I created a category on NSArray that prints out 2D arrays. It's not perfect and can be improved, but it has worked for me.
Header:
#interface NSArray (Logging)
- (void)log2DArray;
#end
Implementation:
#import "NSArray+Logging.h"
#implementation NSArray (Logging)
- (void)log2DArray {
NSMutableString *formattedString = [[NSMutableString alloc] init];
NSInteger longestSubarrayLength = 0;
for (NSArray *subarray in self) {
if (subarray.count > longestSubarrayLength) {
longestSubarrayLength = subarray.count;
}
}
for (int i = 0; i < longestSubarrayLength; i++) {
[formattedString appendFormat:#"\n"];
for (int j = 0; j < self.count; j++) {
NSArray *tempArray = [self objectAtIndex:j];
if (tempArray.count <= longestSubarrayLength) {
[formattedString appendFormat:#"%#\t", [tempArray objectAtIndex:i]];
} else {
[formattedString appendFormat:#"\t"];
}
}
}
NSLog(#"%#", formattedString);
}
#end
Usage:
[myArray log2DArray];
Or use recursiveDescription :)
NSLog(#"my arrays: %#", [myArray recursiveDescription]);