In iOS development, is it possible to use NSString and return it from a function?
e.g.
(NSString * ) foo {
return @"";
}
This is not an objective c method, just function
In iOS development, is it possible to use NSString and return it from a function?
e.g.
(NSString * ) foo {
return @"";
}
This is not an objective c method, just function
Yes, seeing as objective-c objects are just pointers, you can create a C function to return one:
NS_RETURNS_RETAINED NSString *myFunction() {
return [[NSString alloc] init];
}
Notice the use of 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.
If you were returning an autoreleased value, try using NS_RETURNS_NOT_RETAINED instead.
alloc init in the return than I should use NS_RETURNS_RETAINED, and if I return @"xxx" then I should use NS_RETURNS_NOT_RETAINED? What if I don't provide the hints (Assume I am using ARC already)alloc and init, NS_RETURNS_NOT_RETAINED is the default.Yes, but the syntax is different:
NSString *foo()
{
return @"bar";
}
m or mm file or have it's file type attribute set appropriately in Info.static, so that you don't run into linker errors. In fact, it's quite common to have a static inline C function in a header, such as NSMakeRange.@ will be a syntax error.NSString *foo()
{
const char* yourString = "bar";
NSString* yourNSString = [NSString stringWithFormat:@"%s", yourString];
return yourNSString;
}
+stringWithUTF8String: instead.