开发者

Problem in return value on objective-C

please look at this code:

-(NSString *) myfun:(NSString *)name paramnoone:(int)a paramnotwo:(int)b {
    static int numberofcall=0;
    if(a>b) {
        return name;
    }

    NSString *secondname = [[NSString alloc]init];
    secondname = [name StringByAppendingString:@"test"];
    numberofcall++;
    return secondname;
}

i have a problem on it, when my code is on "return secondname" next step is going to "return name" on i开发者_运维问答f statement part, im confusing a lot , because c++ does not have this problem, please help me on solve it, thanks for ur help and sorry for my bad English.


(Until the question is explained further I can't really answer the question, but still have valuable infos which justify being posted as an answer, so here it goes.)

In the line:

NSString *secondname = [[NSString alloc]init];

You allocate an empty string. But in the very next line:

secondname = [name StringByAppendingString:@"test"];

You overwrite the pointer secondname to the previously allocated empty string, thus creating a memory leak. Since you do not use the empty string at all, remove the first line and turn the second line into:

NSString *secondname = [name StringByAppendingString:@"test"];

Edit: Based on comments to the questions, I think what you're asking is this (correct me if I'm wrong):

  • You are debugging the method.
  • While stepping through the method with the debugger, the flow proceeds normally through the method.
  • But after the numberofcall++; line, the debugger suddenly jumps to the return name; instead of the return secondname; line.

If that's what's happening to you: this is normal behavior, unfortunately. When the debugger reaches a return statement the marker always "jumps" to the first return statement in the method. But even though it doesn't look that way, your return secondname; statement is really executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜