【问题标题】:Instance Variable not allocating in memory实例变量未在内存中分配
【发布时间】:2012-09-25 12:33:18
【问题描述】:

我有一个 NSObject 类,其中我定义了一个 init 方法,如下所示,

- (id)initWithPlistName:(NSString *)plistFileName{
    if (self = [super init]) {
        plistName = plistFileName;
        plistContent = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] 
                                                                pathForResource:plistName ofType:@"plist"]]; // this plistContent array is not allocating in memory
    }
    return self;
}

我在我的应用AppDelegate类didFinishLaunchingWithOptions方法中调用这个方法,plistContent是我的iVar键入 NSArray 但只要控制权进入 plistContent alloc init 行并且在返回 self 时,就没有为我的数组分配内存。 这里可能发生了什么问题,提前感谢任何帮助。

【问题讨论】:

  • 你是如何在 appDelegate 中分配初始化对象的
  • 在 appDelegate 中显示你的 didFinish 的 d 代码..
  • 我已经编辑了我的答案,请看..

标签: iphone objective-c ios xcode memory-management


【解决方案1】:

我想您没有将 plist 中 plist 根键的数据类型从字典更改为数组

【讨论】:

    【解决方案2】:

    检查文件是否存在:

    NSString *path = [[NSBundle mainBundle] pathForResource:plistName ofType:@"plist"];
    if(path)
    {
       plistContent = [[NSArray alloc] initWithContentsOfFile:path]; 
    }
    else
    {
      NSLog(@"File Not exists");
    }
    

    【讨论】:

    • 您的答案是正确的,但您不需要使用NSFileManager 进行检查,因为如果文件不存在,pathForResource:ofType 将返回nil。我希望你不介意我编辑你的答案:/
    【解决方案3】:

    试试这个

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"plistName" ofType:@"plist"];
    NSDictionary *myDict = [[NSDictionary alloc] initWithContentsOfFile:filePath];
    NSArray *array = [NSArray arrayWithArray:[myDict objectForKey:@"Root"]];
    

    【讨论】:

      猜你喜欢
      • 2016-01-23
      • 2019-07-13
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2021-10-02
      • 2014-06-01
      相关资源
      最近更新 更多