【问题标题】:NSString with NSInteger [closed]NSString 与 NSInteger [关闭]
【发布时间】:2012-10-19 08:06:32
【问题描述】:

如何将我的 NSInteger 放入我的 NSString stringWithFormat:

我的代码:

-(IBAction)main:(id)sender
{
NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"return the clipboard"];


NSAppleEventDescriptor *clipboardTXT = [[script executeAndReturnError:nil]stringValue];

NSInteger *length = [clipboardTXT.stringValue length];

NSString *mystring = [NSString stringWithFormat:@"%", length];


[mybutton setTitle:mystring];
}

附言我试过this,但它对我不起作用。

output

【问题讨论】:

  • 看到这段代码中的许多错误和你的其他问题,我强烈建议从一本关于编程的好书开始。

标签: objective-c macos nsstring int nsinteger


【解决方案1】:

使用%d 说明符。

- (IBAction)main:(id)sender
{
    NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"return the clipboard"];


    NSAppleEventDescriptor *clipboardTXT = [script executeAndReturnError:nil];

    NSInteger length = [[clipboardTXT stringValue] length];

    NSString *mystring = [NSString stringWithFormat:@"%d", length];

    [mybutton setTitle:mystring];
}

编辑:

您的问题与您所要求的完全不同。为什么第一次没有包含错误消息?浪费时间……

很明显,问题出在您的stringValue 调用附近。如果你用谷歌搜索过,你肯定会发现这个错误消息意味着你发送stringValue 的对象没有这样的方法。 executeAndReturnError 返回一个 NSAppleEventDescriptor 实例。然后调用stringValue,它将返回NSString,而不是NSAppleEventDescriptor。之后,您将向NSString 发送stringValue 消息(它没有这样的方法)。查看我编辑的代码。

【讨论】:

  • 应该的。它做了什么而不是你所期望的?
  • 您不应该使用指针。 length 方法返回一个原始的 NSInteger(不是对象)。看我的回答。
  • @AlexWayne 我添加了我的输出。
  • @s0ulp1xel 实际上,这些代码都没有意义。类型错误,方法错误(因此在您的输出中出现问题),不应该出现的指针,错误/缺少格式说明符...
  • 您还随机混淆了点语法和括号语法。 stringValuelength 都是方法,而不是属性。
【解决方案2】:

两件事,你想使用%d 说明符,你需要在你的长度声明中删除*

NSInteger length = [clipboardTXT.stringValue length];
NSString *mystring = [NSString stringWithFormat:@"%d", length];

【讨论】:

    猜你喜欢
    • 2012-03-13
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2011-12-04
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多