views:

967

answers:

2

Hi Everyone

I've done a fair bit of searching and not really found an answer to my question so was hoping someone might be able to point me in the right direction

I'm new to Objective C and am having a slight issue carrying out something that I would imagine is quite simple; returning an NSArray of objects from a class method

I have the following class with associated class method

@implementation Sale

@synthesize title = _title;
@synthesize description = _description;
@synthesize date = _date;

+(NSArray*)liveSales
{
    NSArray *liveSales = [[NSArray alloc] init];

    for(int i = 0; i < 100; i++)
    {
        Sale *s = [[Sale alloc] init];
        [s setTitle:[NSString stringWithFormat:@"Sale %d", i+1]];
        [s setDescription:[NSString stringWithFormat:@"Sale %d descriptive text", i+1]];

        [liveSales addObject:s];

        [s release];
        s = nil;
    }

    return [liveSales autorelease];
}

@end

And I have a ViewController with the following code (trimmed for ease of reading):

@implementation RootViewController

@synthesize saleList = _saleList;


- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

    [[self saleList] setArray:[Sale liveSales]];
}

The problem I'm experiencing is that the count of saleList is always null so it seems the array is not being set. If I debug the code and step into the class method liveSales there are the correct number of objects in the array at the point of return

Can anyone point me in the right direction?

Thanks :)

Dave

+2  A: 

Probably because saleList is nil to start with. Sending a message to nil in Objective-C (in most cases) does nothing.

Try this instead:

self.saleList = [Sale liveSales];

(assuming the property is declared as retain).

Nicholas Riley
Thanks Nicholas, that seems to have solved the problem I was having. Do you know if there's a way to do without needing to use the dot notation (I'm trying to avoid it was it can get confusing as the code becomes more complex)?
Dave_Stott
`object.property = x` is equivalent to `[object setProperty:x]`. There's nothing confusing about it... they are really equivalent! So, in this case, that would be `[self setSaleList:[Sale liveSales]]`.
Yuji
Thanks Yuji, this achieved exactly what I wanted
Dave_Stott
+4  A: 

First of all, you should allocate an NSMutableArray:

NSMutableArray *liveSales = [[NSMutableArray alloc] init];

The plain NSArray is immutable by definition.

Dirk
Doesn't remotely answer the question, but not bad advice, so +0 I guess.
Chuck
You're right Dirk - I'd already amended the code to use a MutableArray but the behaviour I'm experiencing still exists
Dave_Stott