iosobjective-cnscountedset

NSCountedSet in an if statement


I am trying to NSLog the count of the number of @"1" inside of each label on my ViewController. I created 3 labels on the storyboard, then hooked up the IBOutlet. I added each of these labels into an NSMutableArray and alloc initWithObjects. I manually set the text of each label to be 1, 2, and 3.

Now to my issue.

I want to use a NScountedSet to count the number of 1's inside the array of labels. If the condition is met then NSLog some text.

I created a simple version of the code to highlight the issue.

@property (weak, nonatomic) IBOutlet UILabel *l1;
@property (weak, nonatomic) IBOutlet UILabel *l2;
@property (weak, nonatomic) IBOutlet UILabel *l3;



@property NSMutableArray *dice;

@end

@implementation MainViewController

- (void)viewDidLoad {
[super viewDidLoad];

[self.l1.text isEqualToString:@"1"];
[self.l2.text isEqualToString:@"2"];
[self.l3.text isEqualToString:@"3"];


self.dice = [[NSMutableArray alloc] initWithObjects: self.l1, self.l2,  
self.l3, nil];




NSCountedSet *setOfNumbers = [NSCountedSet setWithObject:self.dice];


if ([setOfNumbers countForObject: @"1"  == 1]) {
    NSLog(@"Count of 1 in array is %lu", (unsigned long) [setOfNumbers  
countForObject:@"1"] );
}

I get 3 warnings...two yellow and 1 red. My teachers told me this wont work and there are other ways to do it. And I have done it the other way. I am just really confused as to why this does not work. I'm only in week 2 of my class.

Can somebody explain why this doesn't work and how I could make it work? Thank you


Solution

  • You have several issues, obviously.

    1. The lines like [self.l1.text isEqualToString:@"1"]; don't do anything. You compare the label's text but don't check the result of the test.
    2. You add the labels instead of the labels' text to the self.dice array.
    3. You have a syntax error on the if line.
    4. You create the counted set with the array instead of the objects in the array.
    5. Store the count from the counted set in a variable so you don't calculate the count twice.

    Here's some fixed code:

    @implementation MainViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
    
        self.dice = [[NSMutableArray alloc] initWithObjects:self.l1.text, self.l2.text, self.l3.text, nil];
    
        NSCountedSet *setOfNumbers = [NSCountedSet setWithArray:self.dice];
    
        NSUInteger count = [setOfNumbers countForObject: @"1"];
        if (count == 1) {
            NSLog(@"Count of 1 in array is %lu", (unsigned long)count);
        }
    }