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 ob开发者_如何学Cjects in the array at the point of return
Can anyone point me in the right direction?
Thanks :)
Dave
First of all, you should allocate an NSMutableArray
:
NSMutableArray *liveSales = [[NSMutableArray alloc] init];
The plain NSArray
is immutable by definition.
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).
精彩评论