// targ_url is passed in as an address to a NSString pointer.
- (long) analyse_scan_result : (NSString *)scan_result target_url : (NSString **)targ_url
{
NSLog (@" RES analyse string : %@", scan_result);
NSRange range = [scan_result rangeOfString : @"http://"
options : NSCaseInsensitiveSearch
];
// **** The following retain is the first retain
// **** statement in this method.
if (range.location == NSNotFound)
{
*targ_url = @"";
[*targ_url retain];
NSLog(@" FND string not found");
return 0;
}
NSString *sub_string = [scan_result substringFromIndex : range.location];
range = [sub_string rangeOfString : @" "];
if (range.location != NSNotFound) {
sub_string = [sub_string substringToIndex : range.location];
}
NSLog(@"FND sub_string = %@", sub_string);
*targ_url = sub_string;
// ** The following retain is the second retain
// ** statement in this method.
[*targ_url retain];
return [*targ_url length];
}
This question is similar and related to the one I asked earlier (which seems to be satisfactorily solved). Again, the above method only works after a retain statement is added. There are 2 added above, but only one is executed at any given time.
What the routine does is to find a “http://” string from a barcode scanner output and return it. My question is are the retain statements necessary or appropriate ?
Hope somebody knowledgable could help…
TL;DR
Do not return owned object values by reference.
Explanation:
By convention, objects returned by reference (or even by value) are not owned unless the method specifically states this. If the method name contains
copyornewthen it is expected to provide an owned reference, otherwise the reference count is considered to be irrelevant.For instance, Cocoa methods that return an
NSErrorby reference return an autoreleasedNSErrorwhich you are not expected to release.What this means is, you can do either, as long as you indicate what you are doing via the method name. You probably just want to return an autoreleased reference and let the caller decide whether they want to keep holding on to it or not.
Apparently, Apple feels you should not return owned values by reference, according to this document:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html