ios developer tiny share-20160817

本文介绍了Objective-C中方法如何返回值及返回对象类型的过程。详细解释了方法返回整型值和对象实例的方式,并通过示例展示了如何使用这些返回值。同时,文中还提到了返回对象的内存管理问题,以及ARC如何帮助开发者处理这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天讲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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值