-4

I want search (to check) one NSString in NSMutableArray. but I dont know about it.

    NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"Marco",@"christian",@"hon",@"John",@"fred",@"asdas", nil];
    NSString *name = @"John";

I want to see is there name variable in a NSMutableArray variable ?

NANNAV
  • 4,875
  • 4
  • 32
  • 50
david
  • 147
  • 3
  • 12
  • [a containsObject:name]; – Aravindhan May 30 '13 at 09:19
  • 1
    I'm voting to close this as too localized. The `containsObject:` function is listed as clear as daylight on the documentation page: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html – borrrden May 30 '13 at 09:21

6 Answers6

4

Use containsObject: method to check this :

NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"Marco",@"christian",@"hon",@"John",@"fred",@"asdas", nil];
    NSString *name = @"John";
    if ([a containsObject:name]) {
        // Your array cotains that object
    }

Hope it helps you.

Nishant Tyagi
  • 9,893
  • 3
  • 40
  • 61
1

run a loop and check .

-(BOOL)array:(NSArray*)array containsString:(NSString*)name
{
    for(NSString *str in array)
    {
        if([name isEqualToString:str])
            return YES;
    }
    return NO;
}

In this way array find out object that it contains.

you can also use a single line

 [array containsObject:name]
Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
1

If you are also interested in the position of your element you can use

 - (NSUInteger)indexOfObject:(id)anObject

it will return NSNotFound if the object is not in the array, or the index of the object

katzenhut
  • 1,742
  • 18
  • 26
1

You can use the following code

if([a containsObject: name])
{
    //here your code
}
manujmv
  • 6,450
  • 1
  • 22
  • 35
0

[a containsObject:name] This might help you.

Desert Rose
  • 3,376
  • 1
  • 30
  • 36
0

I suggest you to use indexOfObject:. Because using this way you can not only check whether it exists but also get the index if it indeed exists.

NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"Marco",@"christian",@"hon",@"John",@"fred",@"asdas", nil];
NSString *name = @"John";
NSInteger index = [array indexOfObject:name];
if (index != NSNotFound) {
    NSLog(@"Find name %@", name);
} else {
    NSLog(@"Name %@ not fount", name);
}
sunkehappy
  • 8,970
  • 5
  • 44
  • 65