简体   繁体   English

NSMutableArray显示(null)/ nil?

[英]NSMutableArray showing (null)/nil?

Hi i have a function like this 嗨,我有这样的功能

- (void)save{
        NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

        paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [paths objectAtIndex:0];
        path = [documentsDirectory stringByAppendingPathComponent:@"NewInAppCustomer.plist"];
        NSMutableArray *MainRoot=[[NSMutableArray alloc]initWithContentsOfFile:path];
        NSMutableDictionary *ContentDictionary=[[NSMutableDictionary alloc]init];
        [ContentDictionary setValue:AppCustomerName  forKey:@"CustomerName"];
        [ContentDictionary setValue:AppAddressLine forKey:@"CustomerAddress"];
        [ContentDictionary setValue:AppPhoneNumber forKey:@"CustomerPhoneNumber"];
        [ContentDictionary setValue:AppPriceTier forKey:@"CustomerPriceTier"];
        [MainRoot addObject:ContentDictionary];
        [MainRoot writeToFile:path atomically:YES];
        NSLog(@"%@",MainRoot);

}

when I print with 当我用

NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

it is showing a correct value, 显示正确的值,

but this line 但是这条线

NSLog(@"%@",MainRoot);

displays nil as its value. 显示nil作为其值。

Can anyone please explain it to me? 有人可以向我解释吗?

This line: 这行:

NSMutableArray *MainRoot=[[NSMutableArray alloc]initWithContentsOfFile:path];

will return nil if: 在以下情况下将返回nil

the file can't be opened or the contents of the file can't be parsed into an array 该文件无法打开或该文件的内容无法解析为数组

so you have a non-existent or an invalid file. 因此您的文件不存在或无效。

So, you should ensure that the file is created before this code runs, or, better, check the result and create a new empty array if you need to. 因此,您应该确保在运行此代码之前已创建文件,或者最好检查结果并根据需要创建一个新的空数组。

if (MainRoot == nil) MainRoot = [NSMutableArray array];

Try this, create the file if it not exist and then write to it 尝试此操作,如果文件不存在,则创建该文件,然后将其写入

- (void)save{
        NSLog(@" %@ %@ %@ %@",AppAddressLine,AppCustomerName,AppPhoneNumber,AppPriceTier);

        paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        documentsDirectory = [paths objectAtIndex:0];
        path = [documentsDirectory stringByAppendingPathComponent:@"NewInAppCustomer.plist"];
        NSMutableArray *mainRoot;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:path]) {

             [fileManager createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:&error];
             mainRoot = [[NSMutableArray alloc] init];
        } else {
             mainRoot = [[NSMutableArray alloc] initWithContentsOfFile:path];
        }
        ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM