0

This is the first time I've used a for loop in iOS! Hurrah!

Please note that "bookTitle" is an NSString object within the class. When this class initiates it takes a String argument and sets bookTitle to that.

books = [[NSMutableArray alloc] initWithObjects:

[[Book alloc] initWithTitle:@"What a great title" andAuthor:@"R Crimson"], 

[[Book alloc] initWithTitle:@"What another great title" andAuthor:@"R Crimson"], 
 nil ];
NSUInteger count = [books count];
for(NSUInteger i= 0; i < count;i++){
    Book *tb= [books objectAtIndex:i];
    if(tb.title=bookTitle){
        nameLabel.text=tb.title;
    }

Sadly both tb.title and bookTitle are null. What should happen is that any object in the array that has a title that matches bookTitle should then have its title assigned to the nameLabel.

So I'm wondering where I've gone wrong, and also if there's a better solution? Because the title attribute isn't a unique identifier, so if I add two objects with the same title to books (unlikely that I ever would, but still!) it'll then return multiple objects, which is no good.

Thanks in advance.

Mo Moosa
  • 937
  • 2
  • 19
  • 39
  • I don't think that the error is in the code you provided. It seems like you are probably not setting the title in your Book init method correctly. Additionally, you should use isEqualToString: for comparing tb.title and bookTitle. = is setting tb.title to bookTitle. isEqualToString: checks if both strings are the same. – enbr Jul 23 '12 at 00:44

1 Answers1

1

You have an error in your if statement.

if (tb.title = bookTitle)

You only have one = in there, so you keep setting tb.title to bookTitle all the time.

But, instead of adding another equal sign, do this:

if ([tb.title isEqualToString:bookTitle]) {
    ...
}

More information here.

Community
  • 1
  • 1
matsr
  • 4,302
  • 3
  • 21
  • 36
  • 1
    Wow, I completely forgot about isEqualToString:. Thanks! I updated my comment above. – enbr Jul 23 '12 at 00:48
  • Excellent, thank you. bookTitle is still null sadly, because I'm having trouble getting the value across from the previous viewcontroller to the second one. I imagine the best way to fix this is to make the firstviewcontroller the second viewcontroller's delegate. Thanks for your help. – Mo Moosa Jul 23 '12 at 01:26