函数可以返回一个对象吗?Objective-C和NSMutableArray

neb*_*lus 1 oop class function objective-c nsmutablearray

我有一个NSMutableArray.它的成员最终成为类中数组实例的成员.我想将NSMutable的实例化放入一个函数中并返回一个数组对象.如果我能做到这一点,我可以让我的一些代码更容易阅读.这可能吗?

这是我想弄清楚的.

//Definition:
function Objects (float a, float b) {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:[NSNumber numberWithFloat:a]];
    [array addObject:[NSNumber numberWithFloat:b]];  
    //[release array]; ????????
    return array;
}

//Declaration:
 Math *operator = [[Math alloc] init];
    [operator findSum:Objects(20.0,30.0)];
Run Code Online (Sandbox Code Playgroud)

如果我在将消息发送到接收方之前实例化NSMutableArray,我的代码就会编译.我知道我可以有一个数组参数和方法.我遇到的问题是如何使用函数并用函数调用替换参数.任何帮助表示赞赏.我对这个概念感兴趣,而不是建议更换findSum方法.

Ale*_*yne 6

使用autorelease返回在方法/函数中创建的对象.

NSMutableArray* Objects(float a, float b) {
    NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
                     // or: [NSMutableArray array];

    [array addObject:[NSNumber numberWithFloat:a]];
    [array addObject:[NSNumber numberWithFloat:b]];  
    return array;
}
Run Code Online (Sandbox Code Playgroud)

或者干脆:

NSMutableArray* Objects(float a, float b) {
    return [NSMutableArray arrayWithObjects:
             [NSNumber numberWithFloat:a],
             [NSNumber numberWithFloat:b],
             nil];
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:`[NSMutableArray array]`是`[[[[NSMutableArray alloc] init] autorelease]`的简写. (3认同)