【问题标题】:Set NSString by reference from another method通过从另一个方法引用设置 NSString
【发布时间】:2016-06-24 16:55:23
【问题描述】:

我有一个通过引用接受 NSString 的方法,其想法是如果发生错误,该字符串将包含特定的错误消息;否则,它将为零。

-(BOOL)doStuffThatCouldProduceAnError:(NSString *)error {
    ...
    // An error occurred, so set the string
    error = @"Foo Bar is invalid"
    return NO;
}

但问题是,doStuffThatCouldProduceAnError 的调用者没有看到错误信息:

-(void)someMethod {
    NSString *error;
    [self doStuffThatCouldProduceAnError:error];
    [NSLog @"Message: %@", error]; // Logs "[nil]"
}

我不确定如何搜索解决方案,并且我尝试搜索的内容并未涵盖通过引用传递和从其他方法进行设置。我也尝试过 NSMutableString,但这似乎没有任何区别。

提前谢谢你!

编辑:我忘了提到我尝试过使用error = [error stringByAppendingString:...],但这也没有用。

【问题讨论】:

    标签: ios objective-c nsstring


    【解决方案1】:

    你不是通过引用传递的。

    你必须这样做

    -(BOOL)doStuffThatCouldProduceAnError:(NSString **)error {
        *error = @"Foo Bar is invalid"
    

    [self doStuffThatCouldProduceAnError:&error];
    

    【讨论】:

    • 在取消引用之前测试NULL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2012-03-07
    • 2013-05-21
    • 2012-12-08
    相关资源
    最近更新 更多