您的位置:首页 > 移动开发 > IOS开发

ios developer tiny share-20160817

2016-08-17 18:06 302 查看
今天讲Objective-C方法返回值,以及Objective-C方法体内的对象类型的local变量的生命周期。

Methods Can Return Values

As well as passing values through method parameters, it’s possible for a method to return a value. Each method shown in this chapter so far has a return type of void. The C void keyword means a method doesn’t return anything.

Specifying a return type of int means that the method returns a scalar integer value:

- (int)magicNumber;

The implementation of the method uses a C return statement to indicate the value that should be passed back after the method has finished executing, like this:
- (int)magicNumber {
return 42;
}

It’s perfectly acceptable to ignore the fact that a method returns a value. In this case the magicNumber method doesn’t do anything useful other than return a value, but there’s nothing wrong with calling the method like this:
[someObject magicNumber];

If you do need to keep track of the returned value, you can declare a variable and assign it to the result of the method call, like this:
int interestingNumber = [someObject magicNumber];

You can return objects from methods in just the same way. The NSString class, for example, offers an uppercaseString method:
- (NSString *)uppercaseString;

It’s used in the same way as a method returning a scalar value, although you need to use a pointer to keep track of the result:
NSString *testString = @"Hello, world!";
NSString *revisedString = [testString uppercaseString];

When this method call returns, revisedString will point to an NSString object representing the characters HELLO WORLD!.
Remember that when implementing a method to return an object, like this:

- (NSString *)magicString {
NSString *stringToReturn = // create an interesting string...

return stringToReturn;
}

the string object continues to exist when it is passed as a return value even though the stringToReturn pointer goes out of scope.

There are some memory management considerations in this situation: a returned object (created on the heap) needs to exist long enough for it to be used by the original caller of the method, but not in perpetuity because that would create a memory leak. For
the most part, the Automatic Reference Counting (ARC) feature of the Objective-C compiler takes care of these considerations for you.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息