当加载plist数据到UITableView时,惰性初始化器从未被调用



我试图加载一个简单的plist文件(在根数组)到UITableView(在一个XCode 4.2选项卡应用程序的第一个视图)。我以前在其他(XCode 3)项目中这样做过,但由于某种原因,似乎我的惰性初始化器数组从未被调用。

.h file:

#import <UIKit/UIKit.h>
@interface NailPolishFirstViewController : UIViewController { 
    NSMutableArray *myCollection;
} 
@property(nonatomic, retain) NSMutableArray *myCollection;
@end

。M文件(相关部分)

#import "NailPolishFirstViewController.h"
@implementation NailPolishFirstViewController
@synthesize myCollection;
// ... 
- (NSMutableArray *) myCollection {
    if (myCollection == nil) {
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:@"database.plist"];
        self.myCollection = [NSMutableArray arrayWithContentsOfFile:finalPath];
        NSLog(@"Collection size: %@", [self.myCollection count]);
    }
    return myCollection;
}
// ... 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Getting rows ... %@", [myCollection count]);
    return [myCollection count];
}
// ...

这个控制器的xib文件附加了一个UITableView,数据源和委托被设置为文件的所有者。

当我构建和运行时,numberOfRowsInSection正在记录"获取行…(null)"但是myCollection的惰性初始化器中的日志从未显示。为什么它从来没有被调用过?

您没有通过访问器。使用[myCollection count]是直接访问ivar,它将是nil。如果你要使用延迟加载,你必须总是通过self.myCollection,否则它永远不会调用你的访问器,永远不会填充记录。

因为myCollection是一个声明的属性,它需要引用它的访问器。试着把它命名为self.myCollection

例如

- (NSMutableArray *) myCollection {
    if (myCollection == nil) {
        NSString *path = [[NSBundle mainBundle] bundlePath];
        NSString *finalPath = [path stringByAppendingPathComponent:@"database.plist"];
        myCollection = [NSMutableArray arrayWithContentsOfFile:finalPath];
        NSLog(@"Collection size: %@", [self.myCollection count]);
    }
    return myCollection;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"Getting rows ... %@", [self.myCollection count]);
    return [self.myCollection count];
}

最新更新