0

I don't understand why, the containsObject method seems to always return NO, here is my method :

-(void)addTockens:(NSString *)tockens
{
    if ([tockens length] == 2 && ![self.tockensArray containsObject:tockens]) {
        [self.tockensArray addObject:tockens];
        NSLog(@"Added");
    }
}  

And here is what I am doing :

TADIgnoringConstraint *ignorer = [TADIgnoringConstraint new];
[ignorer addTockens:@"[]"];
[ignorer addTockens:@"[]"];

I am getting two "Added" in the console even if it shouldn't do that the second time I am trying to add "[]" since "[]" is already in the table.

Pop Flamingo
  • 3,023
  • 2
  • 26
  • 64

1 Answers1

1

I would assume that you are not creating an instance for self.tockensArray, so everything you ask the tockensArray returns nil (which is NO).

Be sure that you initialise self.tockensArray in your init method.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • tockensArray is declared in the interface file like this : @property NSMutableArray *tockensArray; – Pop Flamingo Apr 23 '14 at 11:25
  • In fact I am new to Objective-C and I don't understand why do I need to initialise self.tockenArray since I already declared it in the interface ? – Pop Flamingo Apr 23 '14 at 11:29
  • 3
    Declaration just says you want somewhere to store a pointer to an instance, but it doesn't create (instantiate) an instance, that is something separate, then you can store the pointer to that instance in your @property – Wain Apr 23 '14 at 11:30
  • 1
    Declaring a property in the interface does only that. The property is `nil` until initialized; e.g. `_tockensArray = [NSMutableArray array];` or the like... – FluffulousChimp Apr 23 '14 at 11:31
  • @TrevörAnneDenise Being new to Objective-C isn't an excuse. Declaration alone isn't acceptable in any OOP language. They all need to be initialized before they can be used. The difference is that in a lot of others, calling a method on an uninitialized object usually results in a crash. It doesn't change the fact that in any OOP language, objects must be initialized before they're ready to be used. – nhgrif Apr 23 '14 at 11:35
  • @Wain Ok thank you, and in my case, where is my init method ? Because I am just creating my object with the new method and then using the addTocken method. – Pop Flamingo Apr 23 '14 at 11:38
  • 1
    Create the `init` method if it doesn't exist – Wain Apr 23 '14 at 11:41
  • @Wain Is it a good alternative to see if self.tockensArray is equal or not to nil directly in my method, and if equal to nil set it with an empty array ? – Pop Flamingo Apr 23 '14 at 11:49
  • Not really, the object should configure itself appropriately before use – Wain Apr 23 '14 at 11:51