简体   繁体   English

如何获取NSTextField的stringValue的字符串长度?

[英]How do I get the string length of the stringValue of an NSTextField?

This is probably a naive question but, how do I get the length of the stringValue of an NSTextField ? 这可能是一个天真的问题,但是,如何获得NSTextFieldstringValue的长度? I tried 我试过了

int len = strlen((char *)[textField stringValue]);

where textField is an NSTextField but it always returns 6 (size of a pointer?). textField是一个NSTextField但它总是返回6(指针的大小?)。 Besides I am sure that there is a more Objective-C way to do what I am after. 此外,我确信有更多的Objective-C方式来做我想要的事情。

See NSString documentation 请参阅NSString文档

NSUInteger length = [[textField stringValue] length];

The crucial thing to realize here is that an NSString is not a char*. 这里要实现的关键是NSString不是char *。 To get a real C-style char*, you need to do something like: 要获得真正的C风格char *,您需要执行以下操作:

const char* ptr = [[textField stringValue]
    cStringUsingEncoding:[NSString defaultCStringEncoding]];

Updated to use default encoding instead of assuming ASCII. 更新为使用默认编码而不是假设ASCII。

stringValue is NSString instance. stringValue是NSString实例。 You may use the next code: 您可以使用下一个代码:

NSUInteger len = [[textField stringValue] length];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM