4th*_*ace 8 iphone memory-management objective-c
我在头文件中定义了一个类级别int.在.m文件中,我有一个方法,我想采取一个int参数,修改它并在调用者处反映修改后的值.例如:
classLevelInt = 2;
[self someMethod:classLevelInt];
//Here, I'd like classLevelInt to equal the value assigned to it in the method
Run Code Online (Sandbox Code Playgroud)
In -someMethod:
- (void)someMethod:(int)anInt{
//do some stuff
if(somecondition){
anInt = 2 + 3; //some operation
}
}
Run Code Online (Sandbox Code Playgroud)
我试过用过
但是从来没有看到classLevelInt方法中的值设置反映在该方法之外.如果不从-someMethod返回新的int值,我怎样才能在方法之外保留classLevelInt的值?或者,如果这不是一个好方法,那么更好的方法是什么?
iam*_*mac 15
您可以将指针传递给classLevelIntas int*.
classLevelInt = 2;
[self someMethod:&classLevelInt];
- (void)someMethod:(int*)anInt {
//do some stuff
if(somecondition){
*anInt = 2 + 3; //some operation
}
}
Run Code Online (Sandbox Code Playgroud)
第二种方式,您可以直接classLevelInt在同一个班级进行更改.
- (void)someMethod {
//do some stuff
if(somecondition){
classLevelInt = 2 + 3; //some operation
}
}
Run Code Online (Sandbox Code Playgroud)
iamamac是正确的,但你也问过是否有更好的方法.
如果可能的话,直接返回值.通过引用通常会引起一些不愉快的"代码味道".
如果你需要返回多个int,也许你真的应该创建一个结构或类来封装数据.
| 归档时间: |
|
| 查看次数: |
3052 次 |
| 最近记录: |