Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Simple iPhone App (iOS7) Refactoring into a Model Creating a Custom Class

Problems with alloc and initializing

Hi there

in step two I have problems because I can't initialize and allocate properly.

My code for step 2 looks like this:

import "Quote.h"

@implementation Quote

  • (NSString *) randomQuote { if (_quotes == nil) { _quotes = [[NSArray alloc] initWithObjects: @"quote a", @"quote b", @"quote c", nil]; } return @"Some Quote"; }

@end

3 Answers

Stone Preston
Stone Preston
42,016 Points

Woopsies. my bad. you need to create a whole new method called quotes. you are putting your current code in the randomQuote method which should look like this:

- (NSString *) randomQuote {

    return @"Some Quote";
}

so take your code out of that method, and create a whole new method called quotes which should return an NSArray and put what you had before in there. sorry. didnt notice you had it in the wrong method at first.

Thanks, now it works fine.

Stone Preston
Stone Preston
42,016 Points
- (NSString *) randomQuote {
    if (_quotes == nil) {
     _quotes = [[NSArray alloc] initWithObjects: @"quote a", @"quote b", @"quote c", nil];
  }
    return @"Some Quote";
}

your alloc and init code looks correct. Its the return statement that is incorrect. you need to return the _quotes variable you allocated and initialized, not a string literal.

#import "Quote.h"

@implementation Quote

- (NSString *) randomQuote {
            if (_quotes == nil) {
            _quotes = [[NSArray alloc] initWithObjects: @"quote a", @"quote b", @"quote c", nil];
      }
    return _quotes;
}

@end

this doesn't work either. It's says: "Bummer! Remember to allocate and initialize the instance variable '_quotes' and return it from the method named 'quotes'."