单例阵列不会存储数据模型

时间:2013-10-24 16:58:48

标签: ios objective-c nsmutablearray singleton

我正在使用单例类(contactStorage)和数据模型(contactModel)来存储联系人列表。我在我的根视图控制器的viewdidload中创建了一个联系对象,并尝试将其添加到NSMutableArray但它不会“粘住”。我已经在addContact过程中记录了传入的对象并且它产生了准确的输出,但是,addObject:c不会将它添加到数组中。对此有何见解?

#import "contactListViewController.h"
#import "contactDetailScreenViewController.h"
#import "ContactModel.h"
#import "contactStorage.h"

@interface contactListViewController ()

@end

@implementation contactListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    ContactModel* c = [[ContactModel alloc] initWithfName:@"Mike" andlName:@"Deasy" andEmail:@"mid31@pitt.edu" andPhone:@"4127154194"];
    [c logContact];


    [[contactStorage shared]addContact:c];
    [[contactStorage shared]saveToFile];
    [c release];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

我的单身人士的代码:

//
//  contactStorage.m
//  contactList
//
//  Created by dev on 10/23/13.
//  Copyright (c) 2013 Deasy, Michael William. All rights reserved.
//

#import "contactStorage.h"

@implementation contactStorage
{

}

@synthesize cList = _cList;

static contactStorage* _myOnlyInstance = nil;
#pragma mark Storage Methods

-(void)addContact: (ContactModel*) c
{
    [c logContact];
    [self.cList addObject:c];
    NSLog(@"%@", _cList);
}


-(ContactModel*)getContact: (NSIndexPath*) index
{
    return [self.cList objectAtIndex:index.row];
}

-(NSMutableArray*)deleteContact: (NSIndexPath*) index
{
    [self.cList removeObjectAtIndex:index.row];
    return self.cList;
}

-(NSMutableArray*)getAllContacts
{
    return self.cList;
}


-(void)saveToFile
{
    NSString* path = [[self documentsPath] stringByAppendingPathComponent:@"data.txt"];
    NSLog(@"%@",path);
    [_cList writeToFile:path atomically:YES];
    NSLog(@"%@", self.cList);
}

#pragma mark Singleton Create

-(id)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"Initing the array");
        _cList = [[NSMutableArray alloc] init];
    }
    return self;
}

+(contactStorage*)shared
{
    if (_myOnlyInstance == nil)
    {
        _myOnlyInstance = [[contactStorage alloc] init];
    }
    return _myOnlyInstance;
}

-(NSString*) documentsPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    return documentsDir;
}

@end

我的contactModel的代码:

//
//  ContactModel.m
//  contactList
//
//  Created by dev on 10/23/13.
//  Copyright (c) 2013 Deasy, Michael William. All rights reserved.
//

#import "ContactModel.h"

@implementation ContactModel
{

}

@synthesize fName = _fName;
@synthesize lName = _lName;
@synthesize email = _email;
@synthesize phone = _phone;

-(void)logContact
{
    NSLog(@"%@", self.fName);
    NSLog(@"%@", self.lName);
    NSLog(@"%@", self.email);
    NSLog(@"%@", self.phone);
}

-(void)dealloc
{
    [_fName release];
    [_lName release];
    [_email release];
    [_phone release];
    [super dealloc];
}

-(id) initWithfName: (NSString*) fName
           andlName: (NSString*) lName
           andEmail: (NSString*) email
           andPhone: (NSString*) phone
{
    self = [super init];
    _fName = [[NSString alloc] initWithString:fName];
    _lName = [[NSString alloc] initWithString:lName];
    _email = [[NSString alloc] initWithString:email];
    _phone = [[NSString alloc] initWithString:phone];
    return self;
}

@end

NSLog输出:

2013-10-24 12:50:35.573 contactList[3097:a0b] Mike
2013-10-24 12:50:35.574 contactList[3097:a0b] Deasy
2013-10-24 12:50:35.575 contactList[3097:a0b] mid31@pitt.edu
2013-10-24 12:50:35.575 contactList[3097:a0b] 4127154194
2013-10-24 12:50:35.576 contactList[3097:a0b] Initing the array
2013-10-24 12:50:35.576 contactList[3097:a0b] Mike
2013-10-24 12:50:35.576 contactList[3097:a0b] Deasy
2013-10-24 12:50:35.577 contactList[3097:a0b] mid31@pitt.edu
2013-10-24 12:50:35.577 contactList[3097:a0b] 4127154194
2013-10-24 12:50:35.578 contactList[3097:a0b] (
    "<ContactModel: 0x8d72720>"
)
2013-10-24 12:50:35.578 contactList[3097:a0b] /Users/dev/Library/Application Support/iPhone Simulator/7.0/Applications/7CFD98F0-C502-49E5-953B-FD43B61EDC38/Documents/data.txt
2013-10-24 12:50:35.579 contactList[3097:a0b] (
    "<ContactModel: 0x8d72720>"
)

1 个答案:

答案 0 :(得分:2)

显然,你的单例成功地将ContactModel对象添加到你的单例数组中(由你的NSLog语句证明)。我认为你的问题源于你没有看到你的文件被保存的事实。

那是因为您尝试使用writeToFile NSMutableArray(试图保存plist文件)。如果您检查writeToFile的返回代码,您会发现它失败了。这是因为您无法编写包含自定义对象的数组的plist。您可能希望使用NSKeyedArchiver,例如:

- (void)saveToFile
{
    NSString* path = [[self documentsPath] stringByAppendingPathComponent:@"cList.dat"];
    BOOL success = [NSKeyedArchiver archiveRootObject:_cList toFile:path];
    NSAssert(success, @"write failed");
}

预测逻辑后续问题,如何阅读文件,您将使用NSKeyedUnarchiver,如下所示:

-(void)loadFromFile
{
    NSString* path = [[self documentsPath] stringByAppendingPathComponent:@"cList.dat"];
    self.cList = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSAssert(_cList, @"read failed");
}

但是,要使其工作,您必须使您的联系模型符合NSCoding协议,即将以下方法添加到该类:

#pragma mark - NSCoding methods

- (NSArray *)propertyNames
{
    return @[@"fName", @"lName", @"email", @"phone"];
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
    // if `super` conforms to `NSCoding`, then use 
    //
    // self = [super initWithCoder:aDecoder];
    //
    // in this case, `super` is `NSObject`, so just call `init`

    self = [super init];

    if (self) {
        for (NSString *key in [self propertyNames]) {
            [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
        }
    }

    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    // if `super` conforms to `NSCoding`, itself, then call `encodeWithCoder` for `super`:
    //
    // [super encodeWithCoder:aCoder];
    //
    // in this case, `super` is `NSObject`, so that is not needed

    for (NSString *key in [self propertyNames]) {
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
}

有关使用存档的详细信息,请参阅Archives and Serializations Programming Guide