开发者

Simple? returning an integer in Objective c/Iphone

开发者 https://www.devze.com 2023-02-17 06:31 出处:网络
I\'ve been puzzling over a quite simple operation, which I have been doing in C++. What I what to do is (I know the code is pointless as we know that a=10, but it is to get my point across) pseudo co

I've been puzzling over a quite simple operation, which I have been doing in C++.

What I what to do is (I know the code is pointless as we know that a=10, but it is to get my point across) pseudo code!:

.h:

int *a;
- (void) doSomeThingWithVariable;
- (int) returningVariable;

.m:

- (void) doSomeThingWithVariable
{
 int a=0;
       for (int i =0;i<10;i++)
       {
         a++;
       }
}
- (int) returningVariable
{
return a;
}

main:

int newA;
ClassName *myObject=[[ClassName alloc]init];

[myObject doSomeThingWithVariable];
n开发者_开发技巧ewA=[myObject returningVariable];

So, what I want is for my function to return a public integer from my class. This is such a simple task I have done it so many times, both in Java and C++, but I keep getting this error:

makes integer from pointer without a cast

or

return from incompatible pointer type

I hope someone can help me, there seems to be no help anywhere regarding this issue (probably because it's SO simple :) )


You've got int *a rather than int a. The * makes it a pointer, so returning a from your method "makes integer from pointer without a cast".

Also, note that the 'a' you declared in -doSomethingWithVariable is a local variable, and therefore not available to your -returnVariable method. -returnVariable is returning the global 'a' that you declared as a pointer in your .h file.

I think that what you're probably trying to do is to use an instance variable in both methods. An instance variable will be accessible only within your class, and will be different for each different instance of the class, and will be common to all methods in that class (for a given instance). You want:

@interface MyClass : NSObject
{
    int a;
}
- (void)doSomethingWithVariable;
- (int)returnVariable;
@end
0

精彩评论

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