flux
flux

Reputation: 395

Objective-C Why is this not working?

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {


        NSMutableString *outputStringSet = [[NSMutableString alloc] init];
        NSMutableString *outputStringArray = [[NSMutableString alloc] init];
        NSMutableSet *mySet = [[NSMutableSet alloc] init];
        NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity: 10];
        int userInput;

        NSLog(@"Enter 10 numbers");

        for( int i = 0; i < 10; i++) {
            scanf("%i", &userInput);
            NSNumber *input = [[NSNumber alloc] initWithInt: userInput];
            [myArray addObject:input];
            if([mySet member: input]) {
                [mySet addObject: input];
            }

        }
        for (int k = 0; k < [myArray count]; k++) {

            [outputStringArray appendFormat:@"%@, ", [myArray objectAtIndex:k]];


        }

        NSLog(@"%@", [outputStringArray substringToIndex:[outputStringArray length] - 2]);

        for (int j = 0; j < [myArray count]; j++) {

            if([mySet containsObject: [myArray objectAtIndex:j]]) {

                [outputStringSet appendFormat:@"%@, ", [myArray objectAtIndex:j]];
            }

            NSLog(@"%@", outputStringSet);

        }
    }


    return 0;
}

Code above prints the array but not the appropriate object in the set
Why?
Please explain clearly. I am a bit of a noob, and couldnt find the answer anywhere else.

thanks

Upvotes: 1

Views: 89

Answers (2)

Cyrille
Cyrille

Reputation: 25144

if([mySet member: input]) {
    [mySet addObject: input];
}

You're adding the object to the set if it’s already in it. You want the reverse: add the object if it's not in it.

Thus:

if ( ! [mySet member:input] )
    [mySet addObject:input];

By the way, you should use containsObject: instead of member: in your test:

containsObject:

Returns a Boolean value that indicates whether a given object is present in the set.

- (BOOL)containsObject:(id)anObject

Edit: you don't even need to test if the object is already in the set before adding it. After all, that's the main purpose of a NSSet: to ensure uniqueness of its objects. So if you add an object twice, the second call will silently be ignored, as the object is alreay in it.

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

Your set is empty because of

   if([mySet member: input]) {
        [mySet addObject: input];
    }  

member:

Determines whether the set contains an object equal to a given object, and returns that object if it is present.

Upvotes: 0

Related Questions