我已经进行了相当多的搜索,但并没有真正找到我的问题的答案,所以希望有人能够为我指明正确的方向
我是 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,则在返回点数组中有正确数量的对象
谁能指出我正确的方向?
谢谢:)
戴夫
最佳答案
首先,你应该分配一个NSMutableArray
:
NSMutableArray *liveSales = [[NSMutableArray alloc] init];
普通 NSArray
根据定义是不可变的。
关于iphone - Objective-C : Return an array of objects from a class method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136284/