Loading quotes: SFApp 加入引文

现在我们有地方来保存每一句引言了,接下来要做的事情就是加载文件,储存引文,随机打印。

这就需要新建一个属性来存储引文了,我用 NSMutableArray 来做,然后把 SFQuote 对象放进去。这里还需要自定义一个初始化器,我把它命名为 initWithFile,用来初始化从 main.m 里那段代码获取的文件。

那么现在我们来看看 SFQuote.h 文件的写法:

#import <Foundation/Foundation.h>
#import "SFQuote.h"
NS_ASSUME_NONNULL_BEGIN
@interface SFApp : NSObject
@property NSMutableArray<SFQuote *> *quotes;
- (instancetype)initWithFile:(NSString*)filename;
@end
NS_ASSUME_NONNULL_END

我在这里又直接用了 NS_ASSUME_NONNULL_BEGIN,因为这里也不应该有任何的空值,当 quotes 为空值时,就应该调用初始化器了。

SFApp 的实现文件里面就要有这样一个初始化器的方法,我们要用这个 stringWithContentsOfFile 初始化器把所有引文转换成 NSString,同时也要检查一下这个文本文档是否存在。接着再次调用 componentsSeparatedByString,把文本和作者分开来,放进创建的 SFQuote 对象里。对象创建完毕之后,就把它放进 quotes 数组里。

这里就是 SFApp.m 文件的写法:

#import "SFApp.h"
@implementation SFApp
- (instancetype)initWithFile:(NSString*)filename {
    if (self = [super init]) {
        // load the quotes filename we were given
        NSError *error;
        NSString *contents = [NSString
stringWithContentsOfFile:filename usedEncoding:nil error:&error];
        if (error != nil) {
            // something went wrong – bail out!
            NSLog(@"Fatal error: %@", [error localizedDescription]);
            exit(0);
}
        // still here? We're good to go!
        NSArray *lines = [contents
componentsSeparatedByString:@"\n"];
        // create an empty array to hold the SFQuotes.
        self.quotes = [NSMutableArray arrayWithCapacity:[lines
count]];
        // loop over all the lines, creating quote objects
        for (NSString *line in lines) {
            SFQuote *quote = [[SFQuote alloc] initWithLine:line];
            if (quote != nil) {
                // we got a valid quote back; add it
                [self.quotes addObject:quote];
} 
}
}
    return self;
}

results matching ""

    No results matching ""