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
Objective-C programming language does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.
Returning an object array has been explained above, but in most cases you don't need to. Simply pass your object array to the method, modify and it will reflect from the called place. There is no pass by value in java. There's no pass by reference in Java.
The value given in the return statement is the value returned by the function or method. In your example, the value in accumulator will be the result of calling the method -add: , like this: double bar = [foo add:3.1]; bar will get the value that was in accumulator .
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With