1
// 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];

}

这个问题与我之前提出的问题相似并且相关(这似乎得到了令人满意的解决)。同样,上述方法仅在添加了保留语句后才有效。上面添加了 2 个,但在任何给定时间只执行一个。

该例程所做的是从条形码扫描仪输出中查找“http://”字符串并将其返回。我的问题是保留语句是必要的还是适当的?

希望有懂行的能帮忙...

4

1 回答 1

2

TL;博士

不要通过引用返回拥有的对象值。

解释:

按照惯例,通过引用(甚至按值)返回的对象是不拥有的,除非该方法明确说明这一点。如果方法名称包含copy或者new它应该提供一个拥有的引用,否则引用计数被认为是不相关的。

例如,NSError通过引用返回的Cocoa 方法会返回一个NSError您不希望释放的 autoreleased。

这意味着,只要您通过方法名称表明您正在做什么,您就可以执行任何一项。您可能只想返回一个自动释放的引用并让调用者决定他们是否要继续持有它。

显然,根据本文档,Apple 认为您不应该通过引用返回拥有的值:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html

于 2012-10-31T23:32:51.607 回答