Reputation: 2412
I'm new in Cocoa.
I have NSString - (e.g) MUSIC . I want to add some new NSString in Array, And want to check something like this
if MUSIC already contained in Array, add Music_1 , after Music_2 and so on.
So I need to be able read that integer from NSString, and append it +1 .
Thanks
Upvotes: 0
Views: 2566
Reputation: 22930
For checking duplicate element in Array you can use -containsObject:
method.
[myArray containsObject:myobject];
If you have very big array keep an NSMutableSet
alongside the array.Check the set for the existence of the item before adding to the array. If it's already in the set, don't add it. If not, add it to both.
If you want unique objects and don't care about insertion order, then don't use the array at all, just use the Set. NSMutableSet
is a more efficient container.
For reading integer from NSString
you can use intValue
method.
[myString intValue];
For appending string with number you can use - (NSString *)stringByAppendingString:(NSString *)aString
or - (NSString *)stringByAppendingFormat:(NSString *)format ...
method.
Upvotes: 1
Reputation: 29767
Check it out:
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"123", @"qqq", nil];
NSString *myString = @"MUSIC";
NSInteger counter = 0;
if ([array containsObject:myString]){
NSString *newString = [NSString stringWithFormat:@"%@_%d", myString, ++counter];
[array addObject:newString];
}
else
[array addObject:myString];
Upvotes: 1
Reputation: 2703
Use
NSString *newString = [myString stringByAppendingString:[NSString stringWithFormat:@"_%i", myInteger]];
if myString is "music", newString will be "music_1" or whatever myInteger is.
EDIT: I seem to have gotten the opposite meaning from the other answer provided. Can you maybe clarify what it is you are asking exactly?
Upvotes: 4
Reputation: 40193
Here's how you convert a string to an int
NSString *myStringContainingInt = @"5";
int myInt = [myStringContainingInt intValue];
myInt += 1;
// So on...
Upvotes: 0