[英]Return NSString from a C function
In iOS development, is it possible to use NSString
and return it from a function? 在iOS开发中,可以使用
NSString
并从函数中返回它吗?
eg 例如
(NSString * ) foo {
return @"";
}
This is not an objective c method, just function 这不是客观的c方法,只是功能
Yes, seeing as objective-c objects are just pointers, you can create a C function to return one: 是的,看到objective-c对象只是指针,您可以创建一个C函数以返回一个:
NS_RETURNS_RETAINED NSString *myFunction() {
return [[NSString alloc] init];
}
Notice the use of NS_RETURNS_RETAINED
. 注意使用
NS_RETURNS_RETAINED
。 This is a hint to ARC and the static analyzer that this function returns a retained value to the receiver, and that it's their responsibility to release it. 这是对ARC和静态分析器的提示,该函数将保留值返回给接收器,并且它们有责任释放该值。
If you were returning an autoreleased value, try using NS_RETURNS_NOT_RETAINED
instead. 如果要返回自动释放的值,请尝试使用
NS_RETURNS_NOT_RETAINED
。
Yes, but the syntax is different: 是的,但是语法不同:
NSString *foo()
{
return @"bar";
}
NSString *foo()
{
const char* yourString = "bar";
NSString* yourNSString = [NSString stringWithFormat:@"%s", yourString];
return yourNSString;
}
Yes, why not? 是的,为什么不? Check
NSStringFromRect()
and similar for a reference. 检查
NSStringFromRect()
和类似的参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.