【问题标题】:parameter is not received in method方法中未接收到参数
【发布时间】:2012-03-09 22:22:42
【问题描述】:

我有一个简单且非常前卫的方法。 如果它不存在,它应该创建一个文件夹。 它需要一个正确声明的字符串参数。

当我使用它并传递一个参数时,接收变量保持为空,这很奇怪,因为 pathTo_Folder 是一个路径。

你知道为什么会这样吗?

//Declaration in .h
- (void) createFolder         : (NSString *) thePath  ;

//The call
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    NSString *homePath = [@"~" stringByExpandingTildeInPath];
    NSString *pathTo_Folder = [NSString stringWithFormat:@"%@/Library/Application Support/prolog/",homePath];
    [self createFolder : pathTo_Folder];
}


//In .m
- (void)    createFolder: thePath {
    BOOL isDir;
    NSFileManager *fileManager = [NSFileManager defaultManager]         ;
    [fileManager fileExistsAtPath:thePath isDirectory: &isDir]          ;

    NSLog(@"Folder '%@' exists: %d",thePath,isDir)                      ;

    if (isDir == FALSE) 
    {
        [fileManager createDirectoryAtPath: thePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
}

【问题讨论】:

  • 你不觉得thePath应该有一个类型吗?

标签: objective-c methods parameters


【解决方案1】:

我的猜测是,由于您没有定义 thePath 的类型,编译器会将其默认为 int,而 int%@ 的打印效果不佳。

【讨论】:

  • 感谢您的建议,我将定义从 .h 复制到 .m 像这样: - (void) createFolder : (NSString *) thePath ;现在它可以工作了。非常感谢。罗纳德---
【解决方案2】:

我没有看到参数 thePath 选择器的任何类型声明,应该是

- (void)    createFolder:(NSString*)thePath {
    BOOL isDir;

您可能没有收到警告,因为它的默认值为id,但这主要可以解决问题。但是在这种情况下,id 类型就可以了,也许这是一些 ObjC 黑魔法..

【讨论】:

    【解决方案3】:

    这有点干净,应该可以工作:

    - (void) createFolder: (NSString *) thePath;
    
    - (void) applicationDidFinishLaunching: (NSNotification *) aNotification
    {
        NSString *appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
      NSUserDomainMask, YES) lastObject];
        [self createFolder: [appSupportDir stringByAppendingPathComponent: @"prolog"]];
    }
    
    - (void) createFolder: (NSString *) thePath 
    {
        BOOL isDir;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath: thePath isDirectory: &isDir]) {
            [fileManager createDirectoryAtPath: thePath withIntermediateDirectories: YES attributes: nil error: nil];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-31
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      相关资源
      最近更新 更多