Duplicate element elimination from NSMutableArray - objective-c

I have an NSMutableArray. I have synthesized it as well. I am adding objects to it from a method by xml extraction of some file names etc. Now in my array there is the occurrence of same elements multiple times. I need to eliminate the multiple objects and get only unique ones. How can this be done? I tried the code below but then there arise some errors.
NSString *AName = [CompleteFileName_string1 substringWithRange:ArtistRange];
[array_artist addObject:AName];
for(int i=0; i < [array_artist count]; i++)
{
if([[array_artist objectAtIndex:i] isEqualToString:[array_artist objectAtIndex:i+1]])
{
[[array_artist objectAtIndex:i+1]=NULL];
}
else
{
}
}
EDIT*** i need to eliminate by ignoring case sensitivity too...

Go With NSSet

Take a tempArray as golbally
When you are adding objects from XML you have to just check
NSString *upCaseString=[stringFromXML uppercaseString];
if(![tempArray containsObject:upCaseString]) {
[array_artist addObject:stringFromXML];
[tempArray addObject:upCaseString];
}

if([[array_artist objectAtIndex:i] &&[array_artist objectAtIndex:i+1] caseInsensitiveCompare:#"True"] == NSOrderedSame])
{
Add element
}

Just simply check if the array contains the object:
if(![yourArray containsObject:stringFromXML])
{
[yourArray addObject:stringFromXML]
}

What about:
NSArray *out = [NSSet setWithArray:in].allObjects;
?

Use Following Code..
First Add All values in array_artist
int i1=0;
tempArray = [NSMutableArray alloc] init];
while (i1 < [array_artist count]) {
if ([tempArray containsObject:[array_artist objectAtIndex:i1]) {
//Do not Add
}
else {
//Add object
[tempArray addObject:array_artist:i1];
}
i1++;
}

Related

Adding objects to an NSmutableArray from a C Array

I have an NSmutable array and I am adding some strings present in the C array to it. By using this method
if (!self.arrayOfVariableNames) {
self.arrayOfVariableNames = [[NSMutableArray alloc] init];
for (int i = 0; i< cols; i++) {
[self.arrayOfVariableNames addObject:[NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding ]];
}
}
else{
[self.arrayOfVariableNames removeAllObjects];
for (int i = 0; i< cols; i++) {
[self.arrayOfVariableNames addObject:[NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding ]];
}
}
Does this method ensure that the objects in the NSmutableArray won't be deallocated when the C array is taken out of memory?
if this array arrayOfVariableNames is becoming Null, then the problem is with the initialisation of the array. Please try to use Lazy loading by doing this:
- (NSArray*)arrayOfVariableNames {
if (!_arrayOfVariableNames) {
_arrayOfVariableNames = [[NSMutableArray alloc] init]; //initialise the array if needed
}
return _arrayOfVariableNames; //else return the already initialized array
}
and please comment out this line in your code: self.arrayOfVariableNames = [[NSMutableArray alloc] init];
****EDIT****
Please find the update code in https://docs.google.com/file/d/0BybTW7Dwp2_vdHhQN1p1UzExdTA/edit?pli=1. Have a look at it.
Yes. NSArray retains anything in it.
But you should stop chaining your NSString creation and instead creat a string a line before adding it to the array. Then check for nil.
Only add it to the array if it is not nil.
Do code defensively.
arrayOfVariableNames will not change when the C array get deallocated.
Make sure that your arrayOfVariableNames variable is strong.
#property (nonatomic, strong) NSMutableArray *arrayOfVariableNames;
if (!self.arrayOfVariableNames)
{
self.arrayOfVariableNames = [[NSMutableArray alloc] init];
}
else
{
[self.arrayOfVariableNames removeAllObjects];
}
for (int i = 0; i< cols; i++)
{
NSString *tempString = [NSString stringWithCString:cArrayOfVariableNames[i] encoding:NSUTF8StringEncoding];
if([tempString length] > 0)
{
[self.arrayOfVariableNames addObject:tempString];
}
else
{
NSLog(#"string is empty");
}
}

how to get a single element from an array by comparing with a string value in xcode?

how to get a single element from an array by comparing with a string value.I have a string in a textfield.I want to compare that textfield string with an array.And i want to get that single element form that array.
If you have an NSArray of NSString's and you just want to see whether or not the text field string is in the array you can use:
NSString *textFieldString; // Contents of my text field
NSArray *myArray; // Array to search
BOOL stringMatches = [myArray containsObject:textFieldString];
If you instead want to know the index of the string in the array use:
NSUInteger index = [myArray indexOfObject:textFieldString];
If index == NSNotFound the array does not contain the text field string.
Use compare: method.
for (int i=0; i<[yourArray count]; i++) {
NSString * string = [yourArray objectAtIndex:i];
if ([textfield.text compare:string]) {
NSLog(#"yes");
break;
}
}
I think it will be helpful to you.
Use isEqualToString: method for campare two String.
for (int i=0; i<[array count]; i++) {
NSString * string = [array objectAtIndex:i];
i if (string isEqualToString:textField.text)
{
NSLog(#"Equal");
}
else
{
NSLog(#"Not Equal");
}
}
use this :
for (NSString * string in yourArray) {
if ([string isEqualToString:textField.text])
{
NSLog(#" They are equal");
}
else
{
NSLog(#" They are not");
}
}

NSNumbers stored in NSMutableArray

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.

Remove items in a for loop without side effects?

Can I remove items that I am looping through in an Objective-C for loop without side effects?
For example, is this ok?
for (id item in items) {
if ( [item customCheck] ) {
[items removeObject:item]; // Is this ok here?
}
No, you'll get an error if you mutate the array while in a fast enumeration for loop. Make a copy of the array, iterate over it, and remove from your original.
NSArray *itemsCopy = [items copy];
for (id item in itemsCopy) {
if ( [item customCheck] )
[items removeObject:item]; // Is this ok here
}
[itemsCopy release];
Nope:
Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.
Options for changing an array that you want to enumerate through are given in Using Enumerators: either copy the array and enumerate through, or build up an index set that you use after the loop.
you can remove like this:
//Create array
NSMutableArray* myArray = [[NSMutableArray alloc] init];
//Add some elements
for (int i = 0; i < 10; i++) {
[myArray addObject:[NSString stringWithFormat:#"i = %i", i]];
}
//Remove some elements =}
for (int i = (int)myArray.count - 1; i >= 0 ; i--) {
if(YES){
[myArray removeObjectAtIndex:i];
}
}

iterate list and remove items from it in objective-c?

Objective-c have a built-in list iterantor via 'for(a in b) syntax that works fine with NSArray and other collections. But is it possible to remove items during such iteration without ugly tricks like
for( int i = 0, i < [array count]; i ++ )
{
if( condition )
{
[array removeItemAtIndex : i];
i --;
}
}
You can iterate array in the reverse order so you won't need to extra adjust index:
for( int i = [array count]-1; i >=0; --i)
{
if( condition )
{
[array removeItemAtIndex : i];
}
}
Or accumulate indexes to delete in indexset while enumerating and then delete all elements at once:
NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
for( int i = 0, i < [array count]; i ++ )
{
if( condition )
{
[indexes addIndex : i];
}
}
[array removeObjectsAtIndexes:indexes];
[indexes release];
I would choose 2nd option because changing array while enumerating may be not a good style (although it won't give you errors in this particular case)
No, mutating a collection while enumerating it is explicitly forbidden. You could add the objects that should be removed to a second temporary mutable array and then, outside the loop, remove the objects in that array from the original with removeObjectsInArray:.
I wouldn't Call it a dirty trick to iterate backwards through the array.
for(int i=array.count-1;i>=0;i--)
if(condition)
[array removeItemAtIndex:i];
If I need it I copy my array and enumerate one while the other is mutating
NSArray *arr = firstArr;
for( int i = [array count]-1, i >=0; --i)
{
if( condition )
{
[firstArr removeItemAtIndex : i];
}
}
but I think Vladimir's example is the better one ;) (just to have all possibilities)