开发者

Simple? returning an integer in Objective c/Iphone

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜