【问题标题】:passing parameters in iOS在 iOS 中传递参数
【发布时间】:2012-10-21 03:43:33
【问题描述】:

我是 iOS 新手,通过值或引用传递参数(我来自 Java/.NEt 背景)让我感到困惑。 你看我有一种实用程序/帮助方法,我传递给它一个 NSMutableDictionary,然后是一个文件位置,并要求它从文件中解压缩数据到我发送它的字典。 这是辅助方法:

 - (void)loadData:(NSMutableDictionary *)dictionary fromFile:(NSString *)fname  {
     dictionary = [ NSKeyedUnarchiver unarchiveObjectWithFile : [ self getFilePath:fname ] ] ;
    if ( [dictionary.allKeys count] < 1 ) {
       NSLog(@"Couldn't load file %@ ", fname);
    }  else  {
      NSLog(@"Loaded data from file %@ successfully", fname );
  }
}

现在我在下面的代码行中调用了这个方法

      [ loadData: dataDict fromFile:@"data.archive"];

现在的问题是,在辅助方法结束时,我有一个名为字典的变量,它确实有值,但它不是我从调用行传递的原始字典。 我做错了什么?

【问题讨论】:

    标签: objective-c ios


    【解决方案1】:

    正如这里所解释的 - Passing arguments by value or by reference in objective C - 在目标 c 中,参数是按值传递的,因此对参数的修改是在修改一个值,而不是在传递的引用的实际值。

    如果你想修改你的字典,你应该在它前面加上 ** 来传递引用的值,然后用 * 访问。

    - (void)loadData:(NSMutableDictionary**)dictionary fromFile:(NSString*)fname  {
    {
        *dictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath:fname]];
        if ([*dictionary.allKeys count] < 1) {
            NSLog(@"Couldn't load file %@ ", fname);
        }  
        else  {
            NSLog(@"Loaded data from file %@ successfully", fname);
        }
    }
    

    注意:这种指针解引用有点古怪,可能应该仅限于 **Error 传递。创建一个新的字典副本内容并返回它可能更有意义。

    【讨论】:

    • 在哪里添加前缀?当我调用方法或接收方法时?
    【解决方案2】:

    我猜问题是 data.archive 不是加载字典值的有效文件格式。如果您想将值存储到文件中,然后将它们加载到字典中,我将在您的应用程序的主包中创建一个 .Plist 文件,您可以将值加载到字典中,如下所示:

    NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
    NSDictionary *dataDictionary = [[NSDictionary alloc] initWithContentsOfFile:dataFile];
    

    【讨论】:

      【解决方案3】:

      dictionaryfname 都是指针,它们是通过传递的。就 C 构造而言,您可以将其称为引用。但是,该语言允许您将该参数重新分配给新指针。

      所以如果我们更详细地看一下:

      - (void)loadData:(NSMutableDictionary *)dictionary << a pointer variable local to the method
              fromFile:(NSString *)fname
      {
        dictionary = << oops! assigned that pointer parameter to a different instance
            [NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath:fname]];
        if ([dictionary.allKeys count] < 1 ) { << new instance will be messaged, NOT the object originally passed by parameter
      

      并涵盖如何完成您的意图:

      [dictionary setDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:[self getFilePath:fname]]];
      

      【讨论】:

        猜你喜欢
        • 2014-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 2012-01-22
        • 2016-02-08
        • 1970-01-01
        相关资源
        最近更新 更多