private array init返回nil

时间:2015-09-14 18:09:54

标签: ios objective-c arrays

我正在使用BNR iOS目标C书中开发的代码初始化对象中的私有NSMutableArray。这是初始化代码:

    //
//  NRCViewStore.m
//  Lifetimer
//
//  Created by Nelson Capes on 9/13/15.
//  Copyright (c) 2015 Nelson Capes. All rights reserved.
//

#import "NRCViewStore.h"
#import "NRCView.h"
@interface NRCViewStore ()
@property (nonatomic) NSMutableArray *privateItems;
@end
@implementation NRCViewStore
+(instancetype)sharedStore
{
    static NRCViewStore *sharedStore;

    if(!sharedStore){
        sharedStore = [[self alloc]initPrivate];
    }
    return sharedStore;
}
-(instancetype)init
{
    self = [super init];

    return self;
}
-(instancetype)initPrivate
{
    self = [super init];
    NSArray *viewList = @[@"seconds", @"minutes", @"hours",
                         @"months", @"days", @"years"];

    if(self){
        _privateItems = [NSMutableArray arrayWithArray:viewList];
    }
    return self;
}
-(NSArray *)allitems
{
    return [self.privateItems copy];
}


@end

但是,当我调用该对象时,返回的数组为nil。对象的调用是这样的:

    #import "NRCViewStoreViewController.h"
#import "NRCViewStore.h"
#import "NRCView.h"

@implementation NRCViewStoreViewController
-(instancetype)init{
    self = [super initWithStyle:UITableViewStylePlain];
    return self;
}
-(instancetype)initWithStyle:(UITableViewStyle)style
{
    return [self init];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger count =[[[NRCViewStore sharedStore]allItems]count];
    return count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:@"NRCViewCell"];

    NSArray *array = [[NRCViewStore sharedStore]allItems];
    NRCView *view = array[indexPath.row];
    cell.textLabel.text = view.viewName;
    return cell;
}

@end

据我了解代码,[NRCViewStore sharedStore]应该同时执行alloc和init,并初始化私有NSMutableArray _privateItems。我在返回self之前在initPrivate中设置了一个断点,并且_privateItems数组被初始化为我想要的。然后调用 - (NSArray *)allItems应该返回初始化的NSMutableArray的副本,该副本对调用者来说是一个NSArray。但是,调用allitems后调用程序中的断点显示返回的数组为nil。我无法解决这个问题,因为我的其他项目中的类似代码(没有私有数组初始化)可以正常工作。

0 个答案:

没有答案
相关问题