Objective C:从类方法返回一个对象数组
问题描述:
我已经做了一些搜索,并且没有真正找到答案,所以希望有人能够指引我朝着正确的方向Objective C:从类方法返回一个对象数组
我是Objective C的新手,并且遇到了一些小问题,我可以想象它很简单;从一个类的方法返回对象的一个NSArray
我有关联的类方法
@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
下面的类和我有一个的ViewController用下面的代码(修剪为了便于阅读):
@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]];
}
我遇到的问题是,saleList的计数总是为空,所以它似乎没有设置数组。如果我调试代码并进入类方法liveSales,那么在返回点有数组中的对象的正确数量
任何人都可以指向正确的方向吗?
谢谢:)
戴夫
答
大概是因为saleList
是nil
开始。在Objective-C中发送消息到nil
(在大多数情况下)不会做任何事情。
试试这个:
self.saleList = [Sale liveSales];
(假设该属性被声明为保留)。
你在'@ interface'中定义了'saleList'是什么?你从编译器得到了什么警告? – Yuji 2010-01-25 23:32:39